vce-shell 0.1.1

VCE Shell layer: command language, builtins, execution coordination
Documentation
//! The shared Windows shell machinery.
//!
//! PowerShell and cmd both need the same things to run a Windows command:
//! resolve a name through the command table, record the invocation as a
//! real process, execute it with the standard streams, and finish the
//! process record — plus Windows path handling and redirect I/O. This
//! module is the single implementation of that machinery; the shells keep
//! their own languages, builtins, and parsing, and delegate the rest here.

use engine::{ActorId, Input, Output, VirtualPath};
use os::ExitStatus;
use os::OperatingSystem as _;
use os::environment::Environment;
use os::windows::Windows;
use os::windows::command::WindowsCommandContext;

/// Resolves a path argument against a working directory, accepting
/// Windows path syntax: backslashes, drive prefixes (`C:\Users\Rey`),
/// forward slashes, and trailing separators are all normalized to the
/// engine's slash form.
pub fn resolve_path(cwd: &VirtualPath, argument: &str) -> Result<VirtualPath, os::OsError> {
    if argument.is_empty() {
        return Err(os::OsError::InvalidPathArgument(argument.to_owned()));
    }
    let normalized = os::windows::path::normalize(argument);
    os::runtime::resolve_path_name(&normalized, cwd)
}

/// The Windows display form of an engine path: `C:\Users\Rey`.
pub fn display_path(path: &VirtualPath) -> String {
    os::windows::path::display(path)
}

/// Runs one external command: resolves it through the command table,
/// records the invocation in the process namespace (`tasklist` observes
/// it), executes it with the given streams, and finishes the record.
///
/// Returns `None` when the name does not resolve; the shell writes its
/// own "not recognized" message with its own phrasing.
#[allow(clippy::too_many_arguments)]
pub fn run_external(
    os: &Windows,
    actor: ActorId,
    cwd: &VirtualPath,
    environment: &Environment,
    name: &str,
    argv: &[String],
    stdin: &mut dyn Input,
    stdout: &mut dyn Output,
    stderr: &mut dyn Output,
) -> Option<ExitStatus> {
    let (_object, binding) = os.resolve(name, actor, cwd, environment)?;
    // Every invocation is a real process: recorded in the process
    // namespace, observable by `tasklist` and removable by `taskkill`,
    // exactly like Unix commands.
    let pid = os.allocate_pid();
    let process = os.record_process(actor, pid, name, &argv[1..], cwd).ok();
    let mut context = WindowsCommandContext {
        os,
        actor,
        cwd,
        argv,
        environment,
        stdin,
        stdout,
        stderr,
    };
    let status = match binding.execute(&mut context) {
        Ok(status) => status,
        Err(error) => {
            let _ = stderr.write(format!("{name}: {error}\n").as_bytes());
            ExitStatus::FAILURE
        }
    };
    if let Some(process) = process {
        let _ = os.finish_process(actor, process, status);
    }
    Some(status)
}

/// Writes redirect output to the virtual filesystem, creating the file
/// (under its parent, which must exist) when needed.
pub fn write_redirect(
    os: &Windows,
    actor: ActorId,
    cwd: &VirtualPath,
    path_str: &str,
    bytes: &[u8],
    append: bool,
) -> Result<(), os::OsError> {
    let path = resolve_path(cwd, path_str)?;
    let engine = os.engine();
    let actor = Some(actor);
    if let Ok(object) = engine.lookup(actor, &path) {
        if append {
            engine.append(actor, object, bytes.to_vec())?;
        } else {
            engine.write(actor, object, bytes.to_vec())?;
        }
        return Ok(());
    }
    let parent_path = path.parent().expect("path has parent").clone();
    let parent = engine.lookup(actor, &parent_path)?;
    let name = engine::Name::new(path.name().expect("path has name"))?;
    engine.create_file(actor, parent, name, Some(bytes.to_vec()))?;
    Ok(())
}

/// Reads a redirect input file's bytes.
pub fn read_redirect(
    os: &Windows,
    actor: ActorId,
    cwd: &VirtualPath,
    path_str: &str,
) -> Option<Vec<u8>> {
    let path = resolve_path(cwd, path_str).ok()?;
    let actor = Some(actor);
    let object = os.engine().lookup(actor, &path).ok()?;
    os.engine().read(actor, object).ok().flatten()
}