Skip to main content

shell/
windows_core.rs

1//! The shared Windows shell machinery.
2//!
3//! PowerShell and cmd both need the same things to run a Windows command:
4//! resolve a name through the command table, record the invocation as a
5//! real process, execute it with the standard streams, and finish the
6//! process record — plus Windows path handling and redirect I/O. This
7//! module is the single implementation of that machinery; the shells keep
8//! their own languages, builtins, and parsing, and delegate the rest here.
9
10use engine::{ActorId, Input, Output, VirtualPath};
11use os::ExitStatus;
12use os::OperatingSystem as _;
13use os::environment::Environment;
14use os::windows::Windows;
15use os::windows::command::WindowsCommandContext;
16
17/// Resolves a path argument against a working directory, accepting
18/// Windows path syntax: backslashes, drive prefixes (`C:\Users\Rey`),
19/// forward slashes, and trailing separators are all normalized to the
20/// engine's slash form.
21pub fn resolve_path(cwd: &VirtualPath, argument: &str) -> Result<VirtualPath, os::OsError> {
22    if argument.is_empty() {
23        return Err(os::OsError::InvalidPathArgument(argument.to_owned()));
24    }
25    let normalized = os::windows::path::normalize(argument);
26    os::runtime::resolve_path_name(&normalized, cwd)
27}
28
29/// The Windows display form of an engine path: `C:\Users\Rey`.
30pub fn display_path(path: &VirtualPath) -> String {
31    os::windows::path::display(path)
32}
33
34/// Runs one external command: resolves it through the command table,
35/// records the invocation in the process namespace (`tasklist` observes
36/// it), executes it with the given streams, and finishes the record.
37///
38/// Returns `None` when the name does not resolve; the shell writes its
39/// own "not recognized" message with its own phrasing.
40#[allow(clippy::too_many_arguments)]
41pub fn run_external(
42    os: &Windows,
43    actor: ActorId,
44    cwd: &VirtualPath,
45    environment: &Environment,
46    name: &str,
47    argv: &[String],
48    stdin: &mut dyn Input,
49    stdout: &mut dyn Output,
50    stderr: &mut dyn Output,
51) -> Option<ExitStatus> {
52    let (_object, binding) = os.resolve(name, actor, cwd, environment)?;
53    // Every invocation is a real process: recorded in the process
54    // namespace, observable by `tasklist` and removable by `taskkill`,
55    // exactly like Unix commands.
56    let pid = os.allocate_pid();
57    let process = os.record_process(actor, pid, name, &argv[1..], cwd).ok();
58    let mut context = WindowsCommandContext {
59        os,
60        actor,
61        cwd,
62        argv,
63        environment,
64        stdin,
65        stdout,
66        stderr,
67    };
68    let status = match binding.execute(&mut context) {
69        Ok(status) => status,
70        Err(error) => {
71            let _ = stderr.write(format!("{name}: {error}\n").as_bytes());
72            ExitStatus::FAILURE
73        }
74    };
75    if let Some(process) = process {
76        let _ = os.finish_process(actor, process, status);
77    }
78    Some(status)
79}
80
81/// Writes redirect output to the virtual filesystem, creating the file
82/// (under its parent, which must exist) when needed.
83pub fn write_redirect(
84    os: &Windows,
85    actor: ActorId,
86    cwd: &VirtualPath,
87    path_str: &str,
88    bytes: &[u8],
89    append: bool,
90) -> Result<(), os::OsError> {
91    let path = resolve_path(cwd, path_str)?;
92    let engine = os.engine();
93    let actor = Some(actor);
94    if let Ok(object) = engine.lookup(actor, &path) {
95        if append {
96            engine.append(actor, object, bytes.to_vec())?;
97        } else {
98            engine.write(actor, object, bytes.to_vec())?;
99        }
100        return Ok(());
101    }
102    let parent_path = path.parent().expect("path has parent").clone();
103    let parent = engine.lookup(actor, &parent_path)?;
104    let name = engine::Name::new(path.name().expect("path has name"))?;
105    engine.create_file(actor, parent, name, Some(bytes.to_vec()))?;
106    Ok(())
107}
108
109/// Reads a redirect input file's bytes.
110pub fn read_redirect(
111    os: &Windows,
112    actor: ActorId,
113    cwd: &VirtualPath,
114    path_str: &str,
115) -> Option<Vec<u8>> {
116    let path = resolve_path(cwd, path_str).ok()?;
117    let actor = Some(actor);
118    let object = os.engine().lookup(actor, &path).ok()?;
119    os.engine().read(actor, object).ok().flatten()
120}