Skip to main content

nu_command/system/
run_external.rs

1use itertools::Itertools;
2use nu_cmd_base::hook::eval_hook;
3use nu_engine::{command_prelude::*, env_to_strings};
4use nu_path::{AbsolutePath, dots::expand_ndots_safe, expand_tilde};
5use nu_protocol::{
6    ByteStream, NuGlob, OutDest, Signals, UseAnsiColoring, did_you_mean,
7    process::{ChildProcess, PostWaitCallback},
8    shell_error::io::IoError,
9};
10use nu_system::{ForegroundChild, kill_by_pid, prepare_background_command};
11use nu_utils::IgnoreCaseExt;
12use pathdiff::diff_paths;
13#[cfg(windows)]
14use std::os::windows::process::CommandExt;
15use std::{
16    borrow::Cow,
17    ffi::{OsStr, OsString},
18    io::Write,
19    path::{Path, PathBuf},
20    process::Stdio,
21    sync::Arc,
22    thread,
23};
24
25#[derive(Clone)]
26pub struct External;
27
28impl Command for External {
29    fn name(&self) -> &str {
30        "run-external"
31    }
32
33    fn description(&self) -> &str {
34        "Runs external command."
35    }
36
37    fn extra_description(&self) -> &str {
38        "All externals are run with this command, whether you call it directly with `run-external external` or use `external` or `^external`.
39If you create a custom command with this name, that will be used instead."
40    }
41
42    fn signature(&self) -> nu_protocol::Signature {
43        Signature::build(self.name())
44            .input_output_types(vec![(Type::Any, Type::Any)])
45            .rest(
46                "command",
47                SyntaxShape::OneOf(vec![SyntaxShape::GlobPattern, SyntaxShape::Any]),
48                "External command to run, with arguments.",
49            )
50            .category(Category::System)
51    }
52
53    fn run(
54        &self,
55        engine_state: &EngineState,
56        stack: &mut Stack,
57        call: &Call,
58        input: PipelineData,
59    ) -> Result<PipelineData, ShellError> {
60        let cwd = engine_state.cwd(Some(stack))?;
61        let rest = call.rest::<Value>(engine_state, stack, 0)?;
62        let name_args = rest.split_first().map(|(x, y)| (x, y.to_vec()));
63
64        let Some((name, mut call_args)) = name_args else {
65            return Err(ShellError::MissingParameter {
66                param_name: "no command given".into(),
67                span: call.head,
68            });
69        };
70
71        let name_str: Cow<str> = match &name {
72            Value::Glob { val, .. } => Cow::Borrowed(val),
73            Value::String { val, .. } => Cow::Borrowed(val),
74            Value::List { vals, .. } => {
75                let Some((first, args)) = vals.split_first() else {
76                    return Err(ShellError::MissingParameter {
77                        param_name: "external command given as list empty".into(),
78                        span: call.head,
79                    });
80                };
81                // Prepend elements in command list to the list of arguments except the first
82                call_args.splice(..0, args.to_vec());
83                first.coerce_str()?
84            }
85            _ => Cow::Owned(name.clone().coerce_into_string()?),
86        };
87
88        let expanded_name = match &name {
89            // Expand tilde and ndots on the name if it's a bare string / glob (#13000)
90            Value::Glob { no_expand, .. } if !*no_expand => {
91                expand_ndots_safe(expand_tilde(&*name_str))
92            }
93            _ => Path::new(&*name_str).to_owned(),
94        };
95
96        let paths = nu_engine::env::path_str(engine_state, stack, call.head).unwrap_or_default();
97
98        // On Windows, the user could have run the cmd.exe built-in commands "assoc"
99        // and "ftype" to create a file association for an arbitrary file extension.
100        // They then could have added that extension to the PATHEXT environment variable.
101        // For example, a nushell script with extension ".nu" can be set up with
102        // "assoc .nu=nuscript" and "ftype nuscript=C:\path\to\nu.exe '%1' %*",
103        // and then by adding ".NU" to PATHEXT. In this case we use the which command,
104        // which will find the executable with or without the extension. If "which"
105        // returns true, that means that we've found the script and we believe the
106        // user wants to use the windows association to run the script. The only
107        // easy way to do this is to run cmd.exe with the script as an argument.
108        // File extensions of .COM, .EXE, .BAT, and .CMD are ignored because Windows
109        // can run those files directly. PS1 files are also ignored and that
110        // extension is handled in a separate block below.
111        let pathext_script_in_windows = if cfg!(windows) {
112            if let Some(executable) = which(&expanded_name, &paths, cwd.as_ref()) {
113                let ext = executable
114                    .extension()
115                    .unwrap_or_default()
116                    .to_string_lossy()
117                    .to_uppercase();
118
119                !["COM", "EXE", "BAT", "CMD", "PS1"]
120                    .iter()
121                    .any(|c| *c == ext)
122            } else {
123                false
124            }
125        } else {
126            false
127        };
128
129        // let's make sure it's a .ps1 script, but only on Windows
130        let (potential_powershell_script, path_to_ps1_executable) = if cfg!(windows) {
131            if let Some(executable) = which(&expanded_name, &paths, cwd.as_ref()) {
132                let ext = executable
133                    .extension()
134                    .unwrap_or_default()
135                    .to_string_lossy()
136                    .to_uppercase();
137                (ext == "PS1", Some(executable))
138            } else {
139                (false, None)
140            }
141        } else {
142            (false, None)
143        };
144
145        // Find the absolute path to the executable. On Windows, set the
146        // executable to "cmd.exe" if it's a CMD internal command. If the
147        // command is not found, display a helpful error message.
148        let executable = if cfg!(windows)
149            && (is_cmd_internal_command(&name_str) || pathext_script_in_windows)
150        {
151            PathBuf::from("cmd.exe")
152        } else if cfg!(windows) && potential_powershell_script && path_to_ps1_executable.is_some() {
153            // If we're on Windows and we're trying to run a PowerShell script, we'll use
154            // `powershell.exe` to run it. We shouldn't have to check for powershell.exe because
155            // it's automatically installed on all modern windows systems.
156            PathBuf::from("powershell.exe")
157        } else {
158            // Determine the PATH to be used and then use `which` to find it - though this has no
159            // effect if it's an absolute path already
160            let Some(executable) = which(&expanded_name, &paths, cwd.as_ref()) else {
161                return Err(command_not_found(
162                    &name_str,
163                    call.head,
164                    engine_state,
165                    stack,
166                    &cwd,
167                ));
168            };
169            executable
170        };
171
172        // Create the command.
173        let mut command = std::process::Command::new(&executable);
174
175        // Configure PWD.
176        command.current_dir(cwd);
177
178        // Configure environment variables.
179        let envs = env_to_strings(engine_state, stack)?;
180        command.env_clear();
181        command.envs(envs);
182
183        // Configure args.
184        let args = eval_external_arguments(engine_state, stack, call_args)?;
185        #[cfg(windows)]
186        if is_cmd_internal_command(&name_str) || pathext_script_in_windows {
187            // The /D flag disables execution of AutoRun commands from registry.
188            // The /C flag followed by a command name instructs CMD to execute
189            // that command and quit.
190            command.args(["/D", "/C", &expanded_name.to_string_lossy()]);
191            for arg in &args {
192                command.raw_arg(escape_cmd_argument(arg)?);
193            }
194        } else if potential_powershell_script {
195            command.args([
196                "-File",
197                &path_to_ps1_executable.unwrap_or_default().to_string_lossy(),
198            ]);
199            command.args(args.into_iter().map(|s| s.item));
200        } else {
201            command.args(args.into_iter().map(|s| s.item));
202        }
203        #[cfg(not(windows))]
204        command.args(args.into_iter().map(|s| s.item));
205
206        // Configure stdout and stderr. If both are set to `OutDest::Pipe`,
207        // we'll set up a pipe that merges two streams into one.
208        //
209        // Do **not** force-pipe bare external stdout for interactive `$ans` capture.
210        // Replacing `Print`/`Inherit` with a pipe steals the TTY from full-screen /
211        // interactive tools (`nvim`, `btm`, etc.): they hang or misbehave because
212        // `isatty(stdout)` is false and `store_byte_stream_prefix` blocks reading the
213        // pipe. Bare externals keep the terminal; `$ans.last` only receives external
214        // bytes when stdout is already redirected into the pipeline (e.g. `^cmd | collect`).
215        let stdout = stack.stdout();
216        let stderr = stack.stderr();
217        let merged_stream = if matches!(stdout, OutDest::Pipe) && matches!(stderr, OutDest::Pipe) {
218            let (reader, writer) =
219                os_pipe::pipe().map_err(|err| IoError::new(err, call.head, None))?;
220            command.stdout(
221                writer
222                    .try_clone()
223                    .map_err(|err| IoError::new(err, call.head, None))?,
224            );
225            command.stderr(writer);
226            Some(reader)
227        } else {
228            if engine_state.is_background_job()
229                && matches!(stdout, OutDest::Inherit | OutDest::Print)
230            {
231                command.stdout(Stdio::null());
232            } else {
233                command.stdout(
234                    Stdio::try_from(stdout).map_err(|err| IoError::new(err, call.head, None))?,
235                );
236            }
237
238            if engine_state.is_background_job()
239                && matches!(stderr, OutDest::Inherit | OutDest::Print)
240            {
241                command.stderr(Stdio::null());
242            } else {
243                command.stderr(
244                    Stdio::try_from(stderr).map_err(|err| IoError::new(err, call.head, None))?,
245                );
246            }
247
248            None
249        };
250
251        // Configure stdin. We'll try connecting input to the child process
252        // directly. If that's not possible, we'll set up a pipe and spawn a
253        // thread to copy data into the child process.
254        let data_to_copy_into_stdin = match input {
255            PipelineData::ByteStream(stream, metadata) => match stream.into_stdio() {
256                Ok(stdin) => {
257                    command.stdin(stdin);
258                    None
259                }
260                Err(stream) => {
261                    command.stdin(Stdio::piped());
262                    Some(PipelineData::byte_stream(stream, metadata))
263                }
264            },
265            PipelineData::Empty => {
266                // MCP and background completions must not inherit the live terminal.
267                if engine_state.is_mcp || stack.suppress_stdin {
268                    command.stdin(Stdio::null());
269                    prepare_background_command(&mut command);
270                } else {
271                    command.stdin(Stdio::inherit());
272                }
273                None
274            }
275            value => {
276                command.stdin(Stdio::piped());
277                Some(value)
278            }
279        };
280
281        // Log the command we're about to run in case it's useful for debugging purposes.
282        log::trace!("run-external spawning: {command:?}");
283
284        // Spawn the child process. On Unix, also put the child process to
285        // foreground if we're in an interactive session.
286        #[cfg(windows)]
287        let child = ForegroundChild::spawn(command);
288        #[cfg(unix)]
289        let child = ForegroundChild::spawn(
290            command,
291            // `suppress_stdin` children are already detached; do not also take
292            // the foreground pgrp from the completion thread.
293            engine_state.is_interactive && !stack.suppress_stdin,
294            engine_state.is_background_job(),
295            &engine_state.pipeline_externals_state,
296        );
297
298        let mut child = child.map_err(|err| {
299            let context = format!("Could not spawn foreground child: {err}");
300            IoError::new_internal(err, context)
301        })?;
302
303        if let Some(thread_job) = engine_state.current_thread_job()
304            && !thread_job.try_add_pid(child.pid())
305        {
306            kill_by_pid(child.pid().into()).map_err(|err| {
307                ShellError::Io(IoError::new_internal(
308                    err,
309                    "Could not spawn external stdin worker",
310                ))
311            })?;
312        }
313
314        // If we need to copy data into the child process, do it now.
315        if let Some(data) = data_to_copy_into_stdin {
316            let stdin = child.as_mut().stdin.take().expect("stdin is piped");
317            let engine_state = engine_state.clone();
318            let stack = stack.clone();
319            thread::Builder::new()
320                .name("external stdin worker".into())
321                .spawn(move || {
322                    let _ = write_pipeline_data(engine_state, stack, data, stdin);
323                })
324                .map_err(|err| {
325                    IoError::new_with_additional_context(
326                        err,
327                        call.head,
328                        None,
329                        "Could not spawn external stdin worker",
330                    )
331                })?;
332        }
333
334        let child_pid = child.pid();
335
336        // Wrap the output into a `PipelineData::byte_stream`.
337        let child = ChildProcess::new(
338            child,
339            merged_stream,
340            matches!(stderr, OutDest::Pipe),
341            call.head,
342            Some(PostWaitCallback::for_job_control(
343                engine_state,
344                Some(child_pid),
345                executable
346                    .as_path()
347                    .file_name()
348                    .and_then(|it| it.to_str())
349                    .map(|it| it.to_string()),
350            )),
351        )?;
352
353        Ok(PipelineData::byte_stream(
354            ByteStream::child(child, call.head),
355            None,
356        ))
357    }
358
359    fn examples(&self) -> Vec<Example<'_>> {
360        vec![
361            Example {
362                description: "Run an external command",
363                example: r#"run-external "echo" "-n" "hello""#,
364                result: None,
365            },
366            Example {
367                description: "Redirect stdout from an external command into the pipeline",
368                example: r#"run-external "echo" "-n" "hello" | split chars"#,
369                result: None,
370            },
371            Example {
372                description: "Redirect stderr from an external command into the pipeline",
373                example: r#"run-external "nu" "-c" "print -e hello" e>| split chars"#,
374                result: None,
375            },
376        ]
377    }
378}
379
380/// Evaluate all arguments, performing expansions when necessary.
381pub fn eval_external_arguments(
382    engine_state: &EngineState,
383    stack: &mut Stack,
384    call_args: Vec<Value>,
385) -> Result<Vec<Spanned<OsString>>, ShellError> {
386    let cwd = engine_state.cwd(Some(stack))?;
387    let mut args: Vec<Spanned<OsString>> = Vec::with_capacity(call_args.len());
388
389    for arg in call_args {
390        let span = arg.span();
391        match arg {
392            // Expand globs passed to run-external
393            Value::Glob { val, no_expand, .. } if !no_expand => args.extend(
394                expand_glob(
395                    &val,
396                    cwd.as_std_path(),
397                    span,
398                    engine_state.signals().clone(),
399                )?
400                .into_iter()
401                .map(|s| s.into_spanned(span)),
402            ),
403            other => args
404                .push(OsString::from(coerce_into_string(engine_state, other)?).into_spanned(span)),
405        }
406    }
407    Ok(args)
408}
409
410/// Custom `coerce_into_string()`, including globs, since those are often args to `run-external`
411/// as well
412fn coerce_into_string(engine_state: &EngineState, val: Value) -> Result<String, ShellError> {
413    match val {
414        Value::List { .. } => Err(ShellError::CannotPassListToExternal {
415            arg: String::from_utf8_lossy(engine_state.get_span_contents(val.span())).into_owned(),
416            span: val.span(),
417        }),
418        Value::Glob { val, .. } => Ok(val),
419        _ => val.coerce_into_string(),
420    }
421}
422
423/// Performs glob expansion on `arg`. If the expansion found no matches or the pattern
424/// is not a valid glob, then this returns the original string as the expansion result.
425///
426/// Note: This matches the default behavior of Bash, but is known to be
427/// error-prone. We might want to change this behavior in the future.
428fn expand_glob(
429    arg: &str,
430    cwd: &Path,
431    span: Span,
432    signals: Signals,
433) -> Result<Vec<OsString>, ShellError> {
434    // For an argument that isn't a glob, just do the `expand_tilde`
435    // and `expand_ndots` expansion
436    if !nu_glob::is_glob_with_backend(arg) {
437        let path = expand_ndots_safe(expand_tilde(arg));
438        return Ok(vec![path.into()]);
439    }
440
441    // We must use `nu_engine::glob_from` here, in order to ensure we get paths from the correct
442    // dir
443    let glob = NuGlob::Expand(arg.to_owned()).into_spanned(span);
444    if let Ok((prefix, matches)) = nu_engine::glob_from(&glob, cwd, span, None, signals.clone()) {
445        let mut result: Vec<OsString> = vec![];
446
447        for m in matches {
448            signals.check(&span)?;
449            if let Ok(arg) = m {
450                let arg = resolve_globbed_path_to_cwd_relative(arg, prefix.as_ref(), cwd);
451                result.push(arg.into());
452            } else {
453                result.push(arg.into());
454            }
455        }
456
457        // FIXME: do we want to special-case this further? We might accidentally expand when they don't
458        // intend to
459        if result.is_empty() {
460            result.push(arg.into());
461        }
462
463        Ok(result)
464    } else {
465        Ok(vec![arg.into()])
466    }
467}
468
469fn resolve_globbed_path_to_cwd_relative(
470    path: PathBuf,
471    prefix: Option<&PathBuf>,
472    cwd: &Path,
473) -> PathBuf {
474    if let Some(prefix) = prefix {
475        if let Ok(remainder) = path.strip_prefix(prefix) {
476            let new_prefix = if let Some(pfx) = diff_paths(prefix, cwd) {
477                pfx
478            } else {
479                prefix.to_path_buf()
480            };
481            new_prefix.join(remainder)
482        } else {
483            path
484        }
485    } else {
486        path
487    }
488}
489
490/// Write `PipelineData` into `writer`. If `PipelineData` is not binary, it is
491/// first rendered using the `table` command.
492///
493/// Note: Avoid using this function when piping data from an external command to
494/// another external command, because it copies data unnecessarily. Instead,
495/// extract the pipe from the `PipelineData::byte_stream` of the first command
496/// and hand it to the second command directly.
497fn write_pipeline_data(
498    mut engine_state: EngineState,
499    mut stack: Stack,
500    data: PipelineData,
501    mut writer: impl Write,
502) -> Result<(), ShellError> {
503    if let PipelineData::ByteStream(stream, ..) = data {
504        stream.write_to(writer)?;
505    } else if let PipelineData::Value(Value::Binary { val, .. }, ..) = data {
506        writer
507            .write_all(&val)
508            .map_err(|err| IoError::new_internal(err, "Could not write pipeline data"))?;
509    } else {
510        stack.start_collect_value();
511
512        // Turn off color as we pass data through
513        Arc::make_mut(&mut engine_state.config).use_ansi_coloring = UseAnsiColoring::False;
514
515        // Invoke the `table` command.
516        let output =
517            crate::Table.run(&engine_state, &mut stack, &Call::new(Span::unknown()), data)?;
518
519        // Write the output.
520        for value in output {
521            let bytes = value.coerce_into_binary()?;
522            writer
523                .write_all(&bytes)
524                .map_err(|err| IoError::new_internal(err, "Could not write pipeline data"))?;
525        }
526    }
527    Ok(())
528}
529
530/// Returns a helpful error message given an invalid command name.
531pub fn command_not_found(
532    name: &str,
533    span: Span,
534    engine_state: &EngineState,
535    stack: &mut Stack,
536    cwd: &AbsolutePath,
537) -> ShellError {
538    // Run the `command_not_found` hook if there is one.
539    if let Some(hook) = &stack.get_config(engine_state).hooks.command_not_found {
540        let mut stack = stack.start_collect_value();
541        // Set a special environment variable to avoid infinite loops when the
542        // `command_not_found` hook triggers itself.
543        let canary = "ENTERED_COMMAND_NOT_FOUND";
544        if stack.has_env_var(engine_state, canary) {
545            return ShellError::ExternalCommand {
546                label: format!(
547                    "Command {name} not found while running the `command_not_found` hook"
548                ),
549                help: "Make sure the `command_not_found` hook itself does not use unknown commands"
550                    .into(),
551                span,
552            };
553        }
554        stack.add_env_var(canary.into(), Value::bool(true, Span::unknown()));
555
556        let output = eval_hook(
557            &mut engine_state.clone(),
558            &mut stack,
559            None,
560            vec![("cmd_name".into(), Value::string(name, span))],
561            hook,
562            "command_not_found",
563        );
564
565        // Remove the special environment variable that we just set.
566        stack.remove_env_var(engine_state, canary);
567
568        match output {
569            Ok(PipelineData::Value(Value::String { val, .. }, ..)) => {
570                return ShellError::ExternalCommand {
571                    label: format!("Command `{name}` not found"),
572                    help: val,
573                    span,
574                };
575            }
576            Err(err) => {
577                return err;
578            }
579            _ => {
580                // The hook did not return a string, so ignore it.
581            }
582        }
583    }
584
585    // If the name is one of the removed commands, recommend a replacement.
586    if let Some(replacement) = crate::removed_commands().get(&name.to_lowercase()) {
587        return ShellError::RemovedCommand {
588            removed: name.to_lowercase(),
589            replacement: replacement.clone(),
590            span,
591        };
592    }
593
594    // Making this a closure allows using return inside instead of nesting if-else's
595    let help = (|| {
596        // The command might be from another module. Try to find it.
597        // Note that built-in command categories are not modules,
598        // hence this won't find `math sqrt` if the user types `sqrt`.
599        if let Some(module) = engine_state.which_module_has_decl(name.as_bytes(), &[]) {
600            let module = String::from_utf8_lossy(module);
601
602            // Is the command already imported?
603            let full_name = format!("{module} {name}");
604            if engine_state.find_decl(full_name.as_bytes(), &[]).is_some() {
605                return format!("Did you mean `{full_name}`?");
606            }
607
608            return format!(
609                "A command with that name exists in module `{module}`. Try importing it with `use`"
610            );
611        }
612
613        // Try to match the name with the search terms of existing commands.
614        let signatures = engine_state.get_signatures_and_declids(false);
615        if let Some((last, others)) = signatures
616            .iter()
617            .map(|(sig, _)| sig)
618            .filter(|sig| {
619                let name = name.to_folded_case(); // do not allocate new strings in any()
620                sig.name
621                    .to_folded_case()
622                    .split_ascii_whitespace() // basically split into words
623                    .contains(name.as_str()) // find this one `math sqrt` from the example above
624                    || sig
625                        .search_terms
626                        .iter()
627                        .any(|term| term.to_folded_case() == name)
628            })
629            .map(|sig| format!("`{}`", sig.name))
630            .collect::<Vec<_>>()
631            .split_last()
632        {
633            let commands = if others.is_empty() {
634                last
635            } else {
636                // other or last
637                // other, other or last
638                &format!("{} or {last}", others.join(", "))
639            };
640
641            return format!("Did you mean {commands}?");
642        }
643
644        // Try a fuzzy search on the names of all existing commands.
645        if let Some(cmd) = did_you_mean(signatures.iter().map(|(sig, _)| &sig.name), name) {
646            // The user is invoking an external command with the same name as a
647            // built-in command. Remind them of this.
648            if cmd == name {
649                return "There is a built-in command with the same name".to_string();
650            }
651
652            return format!("Did you mean `{cmd}`?");
653        }
654
655        // If we find a file, it's likely that the user forgot to set permissions
656        if cwd.join(name).is_file() {
657            return format!(
658                "`{name}` refers to a file that is not executable. Did you forget to set execute permissions?"
659            );
660        }
661
662        // We found nothing useful. Give up and return a generic error message.
663        format!("`{name}` is neither a Nushell built-in or a known external command")
664    })();
665
666    ShellError::ExternalCommand {
667        label: format!("Command `{name}` not found"),
668        help,
669        span,
670    }
671}
672
673/// Searches for the absolute path of an executable by name. `.bat` and `.cmd`
674/// files are recognized as executables on Windows.
675///
676/// This is a wrapper around `which::which_in()` except that, on Windows, it
677/// also searches the current directory before any PATH entries.
678///
679/// Note: the `which.rs` crate always uses PATHEXT from the environment. As
680/// such, changing PATHEXT within Nushell doesn't work without updating the
681/// actual environment of the Nushell process.
682pub fn which(name: impl AsRef<OsStr>, paths: &str, cwd: &Path) -> Option<PathBuf> {
683    #[cfg(windows)]
684    let paths = format!("{};{}", cwd.display(), paths);
685    which::which_in(name, Some(paths), cwd).ok()
686}
687
688/// Returns true if `name` is a (somewhat useful) CMD internal command. The full
689/// list can be found at <https://ss64.com/nt/syntax-internal.html>
690fn is_cmd_internal_command(name: &str) -> bool {
691    const COMMANDS: &[&str] = &[
692        "ASSOC", "CLS", "ECHO", "FTYPE", "MKLINK", "PAUSE", "START", "VER", "VOL",
693    ];
694    COMMANDS.iter().any(|cmd| cmd.eq_ignore_ascii_case(name))
695}
696
697/// Returns true if a string contains CMD special characters.
698fn has_cmd_special_character(s: impl AsRef<[u8]>) -> bool {
699    s.as_ref()
700        .iter()
701        .any(|b| matches!(b, b'<' | b'>' | b'&' | b'|' | b'^'))
702}
703
704/// Escape an argument for CMD internal commands. The result can be safely passed to `raw_arg()`.
705#[cfg_attr(not(windows), allow(dead_code))]
706fn escape_cmd_argument(arg: &Spanned<OsString>) -> Result<Cow<'_, OsStr>, ShellError> {
707    let Spanned { item: arg, span } = arg;
708    let bytes = arg.as_encoded_bytes();
709    if bytes.iter().any(|b| matches!(b, b'\r' | b'\n' | b'%')) {
710        // \r and \n truncate the rest of the arguments and % can expand environment variables
711        Err(ShellError::ExternalCommand {
712            label:
713                "Arguments to CMD internal commands cannot contain new lines or percent signs '%'"
714                    .into(),
715            help: "some characters currently cannot be securely escaped".into(),
716            span: *span,
717        })
718    } else if bytes.contains(&b'"') {
719        // If `arg` is already quoted by double quotes, confirm there's no
720        // embedded double quotes, then leave it as is.
721        if bytes.iter().filter(|b| **b == b'"').count() == 2
722            && bytes.starts_with(b"\"")
723            && bytes.ends_with(b"\"")
724        {
725            Ok(Cow::Borrowed(arg))
726        } else {
727            Err(ShellError::ExternalCommand {
728                label: "Arguments to CMD internal commands cannot contain embedded double quotes"
729                    .into(),
730                help: "this case currently cannot be securely handled".into(),
731                span: *span,
732            })
733        }
734    } else if bytes.contains(&b' ') || has_cmd_special_character(bytes) {
735        // If `arg` contains space or special characters, quote the entire argument by double quotes.
736        let mut new_str = OsString::new();
737        new_str.push("\"");
738        new_str.push(arg);
739        new_str.push("\"");
740        Ok(Cow::Owned(new_str))
741    } else {
742        // FIXME?: what if `arg.is_empty()`?
743        Ok(Cow::Borrowed(arg))
744    }
745}
746
747#[cfg(test)]
748mod test {
749    use super::*;
750    use nu_test_support::{fs::Stub, playground::Playground};
751
752    #[test]
753    fn test_expand_glob() {
754        Playground::setup("test_expand_glob", |dirs, play| {
755            play.with_files(&[Stub::EmptyFile("a.txt"), Stub::EmptyFile("b.txt")]);
756
757            let cwd = dirs.test().as_std_path();
758
759            let actual = expand_glob("*.txt", cwd, Span::test_data(), Signals::empty()).unwrap();
760            let expected = &["a.txt", "b.txt"];
761            assert_eq!(actual, expected);
762
763            let actual = expand_glob("./*.txt", cwd, Span::test_data(), Signals::empty()).unwrap();
764            assert_eq!(actual, expected);
765
766            let actual = expand_glob("'*.txt'", cwd, Span::test_data(), Signals::empty()).unwrap();
767            let expected = &["'*.txt'"];
768            assert_eq!(actual, expected);
769
770            let actual = expand_glob(".", cwd, Span::test_data(), Signals::empty()).unwrap();
771            let expected = &["."];
772            assert_eq!(actual, expected);
773
774            let actual = expand_glob("./a.txt", cwd, Span::test_data(), Signals::empty()).unwrap();
775            let expected = &["./a.txt"];
776            assert_eq!(actual, expected);
777
778            let actual = expand_glob("[*.txt", cwd, Span::test_data(), Signals::empty()).unwrap();
779            let expected = &["[*.txt"];
780            assert_eq!(actual, expected);
781
782            let actual =
783                expand_glob("~/foo.txt", cwd, Span::test_data(), Signals::empty()).unwrap();
784            let home = dirs::home_dir().expect("failed to get home dir");
785            let expected: Vec<OsString> = vec![home.join("foo.txt").into()];
786            assert_eq!(actual, expected);
787        })
788    }
789
790    #[test]
791    fn test_write_pipeline_data() {
792        let mut engine_state = EngineState::new();
793        let stack = Stack::new();
794        let cwd = std::env::current_dir()
795            .unwrap()
796            .into_os_string()
797            .into_string()
798            .unwrap();
799
800        // set the PWD environment variable as it's required now
801        engine_state.add_env_var("PWD".into(), Value::string(cwd, Span::test_data()));
802
803        let mut buf = vec![];
804        let input = PipelineData::empty();
805        write_pipeline_data(engine_state.clone(), stack.clone(), input, &mut buf).unwrap();
806        assert_eq!(buf, b"");
807
808        let mut buf = vec![];
809        let input = PipelineData::value(Value::string("foo", Span::test_data()), None);
810        write_pipeline_data(engine_state.clone(), stack.clone(), input, &mut buf).unwrap();
811        assert_eq!(buf, b"foo");
812
813        let mut buf = vec![];
814        let input = PipelineData::value(Value::binary(b"foo", Span::test_data()), None);
815        write_pipeline_data(engine_state.clone(), stack.clone(), input, &mut buf).unwrap();
816        assert_eq!(buf, b"foo");
817
818        let mut buf = vec![];
819        let input = PipelineData::byte_stream(
820            ByteStream::read(
821                b"foo".as_slice(),
822                Span::test_data(),
823                Signals::empty(),
824                ByteStreamType::Unknown,
825            ),
826            None,
827        );
828        write_pipeline_data(engine_state.clone(), stack.clone(), input, &mut buf).unwrap();
829        assert_eq!(buf, b"foo");
830    }
831}
832
833/// `prepare_background_command` must detach from the controlling terminal/console
834/// so completer subprocesses cannot rewrite reedline's raw-mode state.
835#[cfg(test)]
836mod background_isolation_tests {
837    use nu_system::prepare_background_command;
838    use std::process::{Command, Stdio};
839
840    #[cfg(unix)]
841    #[test]
842    fn setsid_removes_controlling_terminal() {
843        let mut cmd = Command::new("sh");
844        // Subshell so a failed redirect does not exit before the `||` branch.
845        cmd.args([
846            "-c",
847            "(exec 3>/dev/tty) 2>/dev/null && echo has_tty || echo no_tty",
848        ])
849        .stdin(Stdio::null())
850        .stdout(Stdio::piped())
851        .stderr(Stdio::null());
852        prepare_background_command(&mut cmd);
853
854        let output = cmd.output().expect("sh should run");
855        assert_eq!(
856            String::from_utf8_lossy(&output.stdout).trim(),
857            "no_tty",
858            "child must not retain a controlling terminal after setsid"
859        );
860    }
861
862    #[cfg(windows)]
863    #[test]
864    fn create_no_window_has_no_console_window() {
865        // prepare_background_command uses CREATE_NO_WINDOW (required for completions).
866        //
867        // Do **not** probe with `echo.>CON`: opening CON can allocate a console even when
868        // the process was started with CREATE_NO_WINDOW, which false-positives on GHA
869        // (the old DETACHED_PROCESS-oriented check).
870        //
871        // GetConsoleWindow() reports whether a console is associated without allocating one.
872        let mut cmd = Command::new("powershell.exe");
873        cmd.args([
874            "-NoProfile",
875            "-NonInteractive",
876            "-Command",
877            concat!(
878                "Add-Type -Namespace NuBg -Name Native -MemberDefinition '",
879                "[DllImport(\"kernel32.dll\")] public static extern System.IntPtr GetConsoleWindow();",
880                "'; ",
881                "if ([NuBg.Native]::GetConsoleWindow() -eq [System.IntPtr]::Zero) { ",
882                "[Console]::Out.Write('no_console') ",
883                "} else { ",
884                "[Console]::Out.Write('has_console') ",
885                "}",
886            ),
887        ])
888        .stdin(Stdio::null())
889        .stdout(Stdio::piped())
890        .stderr(Stdio::piped());
891        prepare_background_command(&mut cmd);
892
893        let output = cmd.output().expect("powershell should run");
894        let stdout = String::from_utf8_lossy(&output.stdout);
895        let stderr = String::from_utf8_lossy(&output.stderr);
896        let token = stdout
897            .split_whitespace()
898            .find(|t| *t == "no_console" || *t == "has_console")
899            .unwrap_or("");
900        assert_eq!(
901            token, "no_console",
902            "child must have no console window under CREATE_NO_WINDOW; stdout={stdout:?} stderr={stderr}"
903        );
904    }
905}