use engine::{BytesInput, BytesOutput, Input, Output, Pipe, Terminal, Timestamp, VirtualPath};
use os::ExitStatus;
use os::OperatingSystem as _;
use os::environment::Environment;
use os::windows::Windows;
pub struct Cmd<'os> {
os: &'os Windows,
actor: engine::ActorId,
cwd: VirtualPath,
environment: Environment,
exit_request: Option<ExitStatus>,
history: Vec<String>,
}
const WINDOWS_VERSION: &str = "Microsoft Windows [Version 10.0.22631.4317]";
impl<'os> Cmd<'os> {
pub fn new(
os: &'os Windows,
actor: engine::ActorId,
environment: Environment,
) -> Result<Self, os::OsError> {
let user_name = os
.users()
.get(actor.get() as u32)
.map(|user| user.name().to_owned())
.unwrap_or_else(|| "Administrator".to_owned());
let home: VirtualPath = format!("/Users/{user_name}").parse().expect("valid path");
let cwd = if os.engine().lookup(Some(actor), &home).is_ok() {
home
} else {
VirtualPath::root()
};
Ok(Self {
os,
actor,
cwd,
environment,
exit_request: None,
history: Vec::new(),
})
}
pub fn actor(&self) -> engine::ActorId {
self.actor
}
fn resolve_path(&self, argument: &str) -> Result<VirtualPath, os::OsError> {
crate::windows_core::resolve_path(&self.cwd, argument)
}
fn display_path(&self, path: &VirtualPath) -> String {
crate::windows_core::display_path(path)
}
fn run_pipeline(
&mut self,
stages: &[String],
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
if stages.len() == 1 {
return self.run_command(&stages[0], stdin, stdout, stderr);
}
let pipes: Vec<Pipe> = (0..stages.len() - 1).map(|_| Pipe::new()).collect();
let mut last_status = ExitStatus::SUCCESS;
for (index, stage) in stages.iter().enumerate() {
let is_last = index == stages.len() - 1;
if is_last {
let mut pipe_in = pipes[index - 1].input();
last_status = self.run_command(stage, &mut pipe_in, stdout, stderr);
} else {
let mut pipe_out = pipes[index].output();
let pipe_in = if index == 0 {
&mut *stdin
} else {
&mut pipes[index - 1].input()
};
last_status = self.run_command(stage, pipe_in, &mut pipe_out, stderr);
}
}
last_status
}
fn run_command(
&mut self,
text: &str,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let (command_text, redirects) = parse_redirects(text);
let mut captured = BytesOutput::new();
let mut captured_stderr = BytesOutput::new();
let mut stdout_redirect: Option<(String, bool)> = None;
let mut stderr_redirect: Option<(String, bool)> = None;
let mut stdin_redirect: Option<String> = None;
for redirect in redirects {
match redirect.0 {
OutputStream::Stdout => stdout_redirect = Some((redirect.1, redirect.2)),
OutputStream::Stderr => stderr_redirect = Some((redirect.1, redirect.2)),
OutputStream::Stdin => stdin_redirect = Some(redirect.1),
}
}
let effective_stdout: &mut dyn Output = if stdout_redirect.is_some() {
&mut captured
} else {
stdout
};
let effective_stderr: &mut dyn Output = if stderr_redirect.is_some() {
&mut captured_stderr
} else {
stderr
};
let words = split_words(&command_text);
if words.is_empty() {
return ExitStatus::SUCCESS;
}
let mut words: Vec<String> = words.into_iter().map(|word| self.expand(&word)).collect();
if words[0].starts_with('@') && words[0].len() > 1 {
words[0] = words[0][1..].to_owned();
}
if let Some((name, rest)) = split_glued_name(&words[0]) {
words[0] = name.to_owned();
if !rest.is_empty() {
words.insert(1, rest);
}
}
let name = words[0].clone();
let mut redirect_input: Option<BytesInput> = match &stdin_redirect {
Some(path) => self.read_redirect(path).map(BytesInput::new),
None => None,
};
if stdin_redirect.is_some() && redirect_input.is_none() {
let _ = stderr.write(b"The system cannot find the file specified.\n");
return ExitStatus::FAILURE;
}
let effective_stdin: &mut dyn Input = match &mut redirect_input {
Some(input) => input,
None => stdin,
};
let echo_remainder =
if words[0].eq_ignore_ascii_case("echo") || words[0].eq_ignore_ascii_case("@echo") {
let mut remainder = &command_text[words[0].len()..];
if remainder.starts_with(' ') {
remainder = &remainder[1..];
}
Some(self.expand(remainder))
} else {
None
};
if let Some(status) = self.try_builtin(
&name,
&words,
echo_remainder.as_deref(),
effective_stdin,
effective_stdout,
effective_stderr,
) {
let _ = self.flush_redirects(
stdout_redirect,
stderr_redirect,
&captured,
&captured_stderr,
stdout,
stderr,
&name,
);
return status;
}
let status = match crate::windows_core::run_external(
self.os,
self.actor,
&self.cwd,
&self.environment,
&name,
&words,
effective_stdin,
effective_stdout,
effective_stderr,
) {
Some(status) => status,
None => {
let _ = effective_stderr.write(
format!("'{name}' is not recognized as an internal or external command, operable program or batch file.\n")
.as_bytes(),
);
ExitStatus::NOT_FOUND
}
};
let _ = self.flush_redirects(
stdout_redirect,
stderr_redirect,
&captured,
&captured_stderr,
stdout,
stderr,
&name,
);
status
}
#[allow(clippy::too_many_arguments)]
fn flush_redirects(
&self,
stdout_redirect: Option<(String, bool)>,
stderr_redirect: Option<(String, bool)>,
captured: &BytesOutput,
captured_stderr: &BytesOutput,
_stdout: &mut dyn Output,
stderr: &mut dyn Output,
name: &str,
) -> Result<(), ()> {
if let Some((path, append)) = stdout_redirect
&& let Err(error) = self.write_redirect(&path, captured.bytes(), append)
{
let _ = stderr.write(format!("{name}: {error}\n").as_bytes());
return Err(());
}
if let Some((path, append)) = stderr_redirect
&& let Err(error) = self.write_redirect(&path, captured_stderr.bytes(), append)
{
let _ = stderr.write(format!("{name}: {error}\n").as_bytes());
return Err(());
}
Ok(())
}
fn write_redirect(
&self,
path_str: &str,
bytes: &[u8],
append: bool,
) -> Result<(), os::OsError> {
crate::windows_core::write_redirect(self.os, self.actor, &self.cwd, path_str, bytes, append)
}
fn read_redirect(&self, path_str: &str) -> Option<Vec<u8>> {
crate::windows_core::read_redirect(self.os, self.actor, &self.cwd, path_str)
}
fn expand(&self, text: &str) -> String {
let mut out = String::new();
let mut rest = text;
while let Some(start) = rest.find('%') {
out.push_str(&rest[..start]);
let remainder = &rest[start + 1..];
let Some(end) = remainder.find('%') else {
out.push('%');
out.push_str(remainder);
return out;
};
let name = &remainder[..end];
let value = match name.to_ascii_lowercase().as_str() {
"cd" => Some(self.display_path(&self.cwd)),
"errorlevel" => Some(self.environment.get("errorlevel").unwrap_or("0").to_owned()),
_ => {
let name_lower = name.to_ascii_lowercase();
self.environment
.iter()
.find(|(key, _)| key.to_ascii_lowercase() == name_lower)
.map(|(_, value)| value.to_owned())
}
};
match value {
Some(value) => out.push_str(&value),
None => out.push_str(&format!("%{name}%")),
}
rest = &remainder[end + 1..];
}
out.push_str(rest);
out
}
fn try_builtin(
&mut self,
name: &str,
argv: &[String],
echo_remainder: Option<&str>,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> Option<ExitStatus> {
match name.to_ascii_lowercase().as_str() {
"echo" => Some(self.builtin_echo(echo_remainder, stdout)),
"cd" | "chdir" => Some(self.builtin_cd(argv, stdout, stderr)),
"dir" => Some(self.builtin_dir(argv, stdout, stderr)),
"type" => Some(self.builtin_type(argv, stdout, stderr)),
"cls" => Some(self.builtin_cls(stdout)),
"set" => Some(self.builtin_set(argv, stdout, stderr)),
"del" | "erase" => Some(self.builtin_del(argv, stderr)),
"mkdir" | "md" => Some(self.builtin_mkdir(argv, stderr)),
"rmdir" | "rd" => Some(self.builtin_rmdir(argv, stderr)),
"copy" => Some(self.builtin_copy(argv, stdout, stderr)),
"ren" | "rename" => Some(self.builtin_ren(argv, stderr)),
"ver" => Some(self.builtin_ver(stdout)),
"date" => Some(self.builtin_date(stdout)),
"time" => Some(self.builtin_time(stdout)),
"title" | "color" => Some(ExitStatus::SUCCESS),
"pause" => Some(self.builtin_pause(stdout, stdin)),
"more" => Some(self.builtin_more(stdin, stdout)),
"exit" => Some(self.builtin_exit(argv)),
_ => None,
}
}
fn builtin_echo(&self, remainder: Option<&str>, stdout: &mut dyn Output) -> ExitStatus {
let Some(remainder) = remainder else {
let _ = stdout.write(b"ECHO is on.\n");
return ExitStatus::SUCCESS;
};
let mut text = remainder.to_owned();
if text.is_empty() {
let _ = stdout.write(b"ECHO is on.\n");
return ExitStatus::SUCCESS;
}
if text == "." || text == ":" {
text.clear();
}
let _ = stdout.write(format!("{text}\n").as_bytes());
ExitStatus::SUCCESS
}
fn builtin_cd(
&mut self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let Some(target) = argv.get(1) else {
let _ = stdout.write(format!("{}\n", self.display_path(&self.cwd)).as_bytes());
return ExitStatus::SUCCESS;
};
let path = match self.resolve_path(target) {
Ok(path) => path,
Err(_) => {
let _ = stderr.write(b"The system cannot find the path specified.\n");
return ExitStatus::FAILURE;
}
};
if self.os.engine().lookup(Some(self.actor), &path).is_err() {
let _ = stderr.write(b"The system cannot find the path specified.\n");
return ExitStatus::FAILURE;
}
self.cwd = path;
ExitStatus::SUCCESS
}
fn builtin_dir(
&self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let mut bare = false;
let mut target: Option<&str> = None;
for argument in argv.iter().skip(1) {
if argument == "/b" || argument == "/B" {
bare = true;
} else if argument.starts_with('/') {
let _ = stderr.write(format!("Invalid switch - {argument}.\n").as_bytes());
return ExitStatus::FAILURE;
} else {
target = Some(argument);
}
}
let path = match target {
Some(target) => match self.resolve_path(target) {
Ok(path) => path,
Err(_) => {
let _ = stderr.write(b"The system cannot find the path specified.\n");
return ExitStatus::FAILURE;
}
},
None => self.cwd.clone(),
};
let actor = Some(self.actor);
let engine = self.os.engine();
let Ok(object) = engine.lookup(actor, &path) else {
let _ = stderr.write(b"The system cannot find the path specified.\n");
return ExitStatus::FAILURE;
};
if !bare {
let _ = stdout.write(b" Volume in drive C has no label\n");
let _ =
stdout.write(format!(" Directory of {}\n\n", self.display_path(&path)).as_bytes());
}
let mut files = 0u64;
let mut dirs = 0u64;
let Ok(children) = engine.children(actor, object) else {
return ExitStatus::SUCCESS;
};
for child in children {
let Ok(metadata) = engine.metadata(actor, child) else {
continue;
};
let is_dir = engine.children(actor, child).is_ok();
let name = metadata.name().as_str().to_owned();
let size = engine.size(actor, child).unwrap_or(0);
let date = os::datetime::format_timestamp(metadata.modified(), "%m/%d/%Y");
let hour = metadata.modified().as_nanos() / 3_600_000_000_000 % 12;
let minute = (metadata.modified().as_nanos() / 60_000_000_000) % 60;
let ampm = if metadata.modified().as_nanos() / 3_600_000_000_000 % 24 < 12 {
"AM"
} else {
"PM"
};
let hour = if hour == 0 { 12 } else { hour };
if bare {
let _ = stdout.write(format!("{name}\n").as_bytes());
} else if is_dir {
dirs += 1;
let _ = stdout.write(
format!("{date} {hour:02}:{minute:02} {ampm} <DIR> {name}\n")
.as_bytes(),
);
} else {
files += 1;
let _ = stdout.write(
format!("{date} {hour:02}:{minute:02} {ampm} {size:>14} {name}\n")
.as_bytes(),
);
}
}
let _ = stdout
.write(format!("\n {files} File(s) {files} bytes\n").as_bytes());
let _ = stdout.write(format!(" {dirs} Dir(s) \n").as_bytes());
ExitStatus::SUCCESS
}
fn builtin_type(
&self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let Some(target) = argv.get(1) else {
let _ = stderr.write(b"The syntax of the command is incorrect.\n");
return ExitStatus::FAILURE;
};
let path = match self.resolve_path(target) {
Ok(path) => path,
Err(_) => {
let _ = stderr.write(b"The system cannot find the file specified.\n");
return ExitStatus::FAILURE;
}
};
let actor = Some(self.actor);
let Ok(object) = self.os.engine().lookup(actor, &path) else {
let _ = stderr.write(b"The system cannot find the file specified.\n");
return ExitStatus::FAILURE;
};
match self.os.engine().read(actor, object) {
Ok(Some(bytes)) => {
let _ = stdout.write(&bytes);
ExitStatus::SUCCESS
}
_ => {
let _ = stderr.write(b"The system cannot find the file specified.\n");
ExitStatus::FAILURE
}
}
}
fn builtin_cls(&self, stdout: &mut dyn Output) -> ExitStatus {
let _ = stdout.write(b"\x1b[3J\x1b[H\x1b[2J");
ExitStatus::SUCCESS
}
fn builtin_set(
&mut self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
if argv.len() == 1 {
let mut entries: Vec<(String, String)> = self
.environment
.iter()
.map(|(key, value)| (key.to_owned(), value.to_owned()))
.collect();
entries.sort();
for (key, value) in entries {
let _ = stdout.write(format!("{key}={value}\n").as_bytes());
}
return ExitStatus::SUCCESS;
}
let assignment = &argv[1];
let Some((name, value)) = assignment.split_once('=') else {
let prefix = assignment.to_ascii_lowercase();
let mut found = false;
let mut entries: Vec<(String, String)> = self
.environment
.iter()
.filter(|(key, _)| key.to_ascii_lowercase().starts_with(&prefix))
.map(|(key, value)| (key.to_owned(), value.to_owned()))
.collect();
entries.sort();
for (key, value) in entries {
found = true;
let _ = stdout.write(format!("{key}={value}\n").as_bytes());
}
if !found {
let _ = stderr
.write(format!("Environment variable {assignment} not defined\n").as_bytes());
return ExitStatus::FAILURE;
}
return ExitStatus::SUCCESS;
};
if name.is_empty() {
let _ = stderr.write(b"The syntax of the command is incorrect.\n");
return ExitStatus::FAILURE;
}
if value.is_empty() {
self.environment.remove(name);
} else {
self.environment.set(name, value);
}
ExitStatus::SUCCESS
}
fn builtin_del(&self, argv: &[String], stderr: &mut dyn Output) -> ExitStatus {
let mut exit_status = ExitStatus::SUCCESS;
for target in argv.iter().skip(1).filter(|arg| !arg.starts_with('/')) {
let path = match self.resolve_path(target) {
Ok(path) => path,
Err(_) => {
let _ = stderr.write(b"The system cannot find the file specified.\n");
exit_status = ExitStatus::FAILURE;
continue;
}
};
let actor = Some(self.actor);
match self.os.engine().lookup(actor, &path) {
Ok(object) => {
let _ = self.os.engine().delete(actor, object);
}
Err(_) => {
let _ = stderr.write(b"The system cannot find the file specified.\n");
exit_status = ExitStatus::FAILURE;
}
}
}
exit_status
}
fn builtin_mkdir(&self, argv: &[String], stderr: &mut dyn Output) -> ExitStatus {
let Some(target) = argv.iter().skip(1).find(|arg| !arg.starts_with('/')) else {
let _ = stderr.write(b"The syntax of the command is incorrect.\n");
return ExitStatus::FAILURE;
};
let path = match self.resolve_path(target) {
Ok(path) => path,
Err(_) => {
let _ = stderr.write(b"The system cannot find the path specified.\n");
return ExitStatus::FAILURE;
}
};
let actor = Some(self.actor);
let engine = self.os.engine();
let mut current = VirtualPath::root();
for segment in path.segments() {
current = current.join(&engine::Name::new(segment).expect("valid name"));
if engine.lookup(actor, ¤t).is_err() {
let parent = current
.parent()
.and_then(|parent| engine.lookup(actor, &parent).ok())
.unwrap_or(engine.root());
let name = engine::Name::new(segment).expect("valid name");
if let Err(error) = engine.create_directory(actor, parent, name) {
let _ = stderr.write(format!("mkdir: {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
}
}
ExitStatus::SUCCESS
}
fn builtin_rmdir(&self, argv: &[String], stderr: &mut dyn Output) -> ExitStatus {
let Some(target) = argv.iter().skip(1).find(|arg| !arg.starts_with('/')) else {
let _ = stderr.write(b"The syntax of the command is incorrect.\n");
return ExitStatus::FAILURE;
};
let path = match self.resolve_path(target) {
Ok(path) => path,
Err(_) => {
let _ = stderr.write(b"The system cannot find the path specified.\n");
return ExitStatus::FAILURE;
}
};
let actor = Some(self.actor);
let Ok(object) = self.os.engine().lookup(actor, &path) else {
let _ = stderr.write(b"The system cannot find the path specified.\n");
return ExitStatus::FAILURE;
};
if self.os.engine().children(actor, object).is_ok()
&& !self.os.engine().children(actor, object).unwrap().is_empty()
{
let _ = stderr.write(b"The directory is not empty.\n");
return ExitStatus::FAILURE;
}
match self.os.engine().delete(actor, object) {
Ok(()) => ExitStatus::SUCCESS,
Err(_) => {
let _ = stderr.write(b"The system cannot find the path specified.\n");
ExitStatus::FAILURE
}
}
}
fn builtin_copy(
&self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let operands: Vec<&String> = argv
.iter()
.skip(1)
.filter(|argument| !argument.starts_with('/'))
.collect();
if operands.len() < 2 {
let _ = stderr.write(b"The syntax of the command is incorrect.\n");
return ExitStatus::FAILURE;
}
let source = match self.resolve_path(operands[0]) {
Ok(path) => path,
Err(_) => {
let _ = stderr.write(b"The system cannot find the file specified.\n");
return ExitStatus::FAILURE;
}
};
let destination = match self.resolve_path(operands[1]) {
Ok(path) => path,
Err(_) => {
let _ = stderr.write(b"The system cannot find the file specified.\n");
return ExitStatus::FAILURE;
}
};
let actor = Some(self.actor);
let engine = self.os.engine();
let Ok(source_object) = engine.lookup(actor, &source) else {
let _ = stderr.write(b"The system cannot find the file specified.\n");
return ExitStatus::FAILURE;
};
let Some(bytes) = engine.read(actor, source_object).ok().flatten() else {
let _ = stderr.write(b"The system cannot find the file specified.\n");
return ExitStatus::FAILURE;
};
let result = if let Ok(destination_object) = engine.lookup(actor, &destination) {
engine.write(actor, destination_object, bytes)
} else {
let parent_path = destination.parent().expect("path has parent").clone();
match engine.lookup(actor, &parent_path) {
Ok(parent) => {
let name = engine::Name::new(destination.name().expect("path has name"));
match name {
Ok(name) => engine
.create_file(actor, parent, name, Some(bytes))
.map(|_| ()),
Err(_) => Err(engine::Error::PathNotFound(destination.clone())),
}
}
Err(_) => Err(engine::Error::PathNotFound(destination.clone())),
}
};
match result {
Ok(()) => {
let _ = stdout.write(b" 1 file(s) copied.\n");
ExitStatus::SUCCESS
}
Err(_) => {
let _ = stderr.write(b"The system cannot find the file specified.\n");
ExitStatus::FAILURE
}
}
}
fn builtin_ren(&self, argv: &[String], stderr: &mut dyn Output) -> ExitStatus {
let operands: Vec<&String> = argv
.iter()
.skip(1)
.filter(|argument| !argument.starts_with('/'))
.collect();
if operands.len() != 2 {
let _ = stderr.write(b"The syntax of the command is incorrect.\n");
return ExitStatus::FAILURE;
}
let path = match self.resolve_path(operands[0]) {
Ok(path) => path,
Err(_) => {
let _ = stderr.write(b"The system cannot find the file specified.\n");
return ExitStatus::FAILURE;
}
};
let new_name = match engine::Name::new(operands[1]) {
Ok(name) => name,
Err(_) => {
let _ = stderr.write(b"The syntax of the command is incorrect.\n");
return ExitStatus::FAILURE;
}
};
let actor = Some(self.actor);
let engine = self.os.engine();
let Ok(object) = engine.lookup(actor, &path) else {
let _ = stderr.write(b"The system cannot find the file specified.\n");
return ExitStatus::FAILURE;
};
let parent = engine
.parent(actor, object)
.ok()
.flatten()
.unwrap_or(engine.root());
match engine.move_object(actor, object, parent, Some(new_name)) {
Ok(()) => ExitStatus::SUCCESS,
Err(_) => {
let _ =
stderr.write(b"A duplicate file name exists, or the file cannot be found.\n");
ExitStatus::FAILURE
}
}
}
fn builtin_ver(&self, stdout: &mut dyn Output) -> ExitStatus {
let _ = stdout.write(format!("{WINDOWS_VERSION}\n").as_bytes());
ExitStatus::SUCCESS
}
fn builtin_date(&self, stdout: &mut dyn Output) -> ExitStatus {
let now = self.os.engine().time();
let _ = stdout.write(
format!(
"The current date is: {}\n",
os::datetime::format_timestamp(now, "%a %m/%d/%Y")
)
.as_bytes(),
);
ExitStatus::SUCCESS
}
fn builtin_time(&self, stdout: &mut dyn Output) -> ExitStatus {
let now = self.os.engine().time();
let seconds = now.as_nanos() / 1_000_000_000;
let hour24 = (seconds / 3600) % 24;
let minute = (seconds % 3600) / 60;
let second = seconds % 60;
let hour12 = hour24 % 12;
let hour12 = if hour12 == 0 { 12 } else { hour12 };
let ampm = if hour24 < 12 { "AM" } else { "PM" };
let _ = stdout.write(
format!("The current time is: {hour12:02}:{minute:02}:{second:02}.00 {ampm}\n")
.as_bytes(),
);
ExitStatus::SUCCESS
}
fn builtin_pause(&self, stdout: &mut dyn Output, stdin: &mut dyn Input) -> ExitStatus {
let _ = stdout.write(b"Press any key to continue . . .");
let mut line = String::new();
let _ = stdin.read_line(&mut line);
let _ = stdout.write(b"\n");
ExitStatus::SUCCESS
}
fn builtin_more(&self, stdin: &mut dyn Input, stdout: &mut dyn Output) -> ExitStatus {
let mut buffer = [0u8; 4096];
loop {
match stdin.read(&mut buffer) {
Ok(0) => break,
Ok(count) => {
if stdout.write(&buffer[..count]).is_err() {
return ExitStatus::FAILURE;
}
}
Err(_) => return ExitStatus::FAILURE,
}
}
ExitStatus::SUCCESS
}
fn builtin_exit(&mut self, argv: &[String]) -> ExitStatus {
let argument = argv
.iter()
.skip(1)
.find(|argument| !argument.eq_ignore_ascii_case("/b"));
let code = argument
.and_then(|value| value.trim().parse::<i64>().ok())
.map_or(0, |value| u8::try_from(value & 0xFF).unwrap_or(0));
let status = ExitStatus::new(code);
self.exit_request = Some(status);
status
}
}
fn split_glued_name(word: &str) -> Option<(String, String)> {
let lower = word.to_ascii_lowercase();
for name in [
"echo", "cd", "chdir", "dir", "type", "cls", "set", "del", "erase", "mkdir", "md", "rmdir",
"rd", "copy", "ren", "rename", "ver", "date", "time", "title", "color", "pause", "exit",
"more",
] {
if lower.starts_with(name) && lower.len() > name.len() {
return Some((word[..name.len()].to_owned(), word[name.len()..].to_owned()));
}
}
None
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum OutputStream {
Stdout,
Stderr,
Stdin,
}
fn split_words(text: &str) -> Vec<String> {
let mut words = Vec::new();
let mut current = String::new();
let mut quoted = false;
for ch in text.chars() {
match ch {
'"' => quoted = !quoted,
' ' | '\t' if !quoted => {
if !current.is_empty() {
words.push(std::mem::take(&mut current));
}
}
_ => current.push(ch),
}
}
if !current.is_empty() {
words.push(current);
}
words
}
fn parse_redirects(text: &str) -> (String, Vec<(OutputStream, String, bool)>) {
let mut command = String::new();
let mut redirects = Vec::new();
let mut chars = text.chars().peekable();
let mut quoted = false;
while let Some(ch) = chars.next() {
match ch {
'"' => {
quoted = !quoted;
command.push(ch);
}
'>' | '<' | '2' if !quoted => {
if ch == '2' {
if matches!(chars.peek(), Some('>')) {
chars.next();
let append = chars.peek() == Some(&'>');
if append {
chars.next();
}
let target = read_redirect_target(&mut chars);
redirects.push((OutputStream::Stderr, target, append));
continue;
}
command.push(ch);
continue;
}
let stream = if ch == '<' {
OutputStream::Stdin
} else {
OutputStream::Stdout
};
let append = if stream == OutputStream::Stdout {
chars.peek() == Some(&'>')
} else {
false
};
if append {
chars.next();
}
let target = read_redirect_target(&mut chars);
redirects.push((stream, target, append));
}
_ => command.push(ch),
}
}
(command.trim().to_owned(), redirects)
}
fn read_redirect_target(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> String {
while chars.peek().is_some_and(|ch| matches!(ch, ' ' | '\t')) {
chars.next();
}
let mut target = String::new();
while let Some(&ch) = chars.peek() {
match ch {
'"' => {
chars.next();
}
' ' | '\t' => break,
'>' | '<' => break,
_ => {
chars.next();
target.push(ch);
}
}
}
target
}
fn split_line(line: &str) -> Vec<(Option<Separator>, Vec<String>)> {
let mut statements: Vec<(Option<Separator>, Vec<String>)> = Vec::new();
let mut stages: Vec<String> = Vec::new();
let mut current = String::new();
let mut quoted = false;
let mut pending: Option<Separator> = None;
let mut chars = line.chars().peekable();
while let Some(ch) = chars.next() {
match ch {
'"' => {
quoted = !quoted;
current.push(ch);
}
'&' | '|' if !quoted => {
let next = chars.peek();
let (separator, consumed) = match (ch, next) {
('&', Some('&')) => (Separator::AndAnd, true),
('|', Some('|')) => (Separator::OrOr, true),
('&', _) => (Separator::Always, false),
('|', _) => (Separator::Pipe, false),
_ => unreachable!(),
};
if consumed {
chars.next();
}
if !current.trim().is_empty() {
stages.push(current.trim().to_owned());
}
current.clear();
if separator == Separator::Pipe {
continue;
}
if !stages.is_empty() {
statements.push((pending.take(), std::mem::take(&mut stages)));
}
pending = Some(separator);
}
_ => current.push(ch),
}
}
if !current.trim().is_empty() {
stages.push(current.trim().to_owned());
}
if !stages.is_empty() {
statements.push((pending.take(), stages));
}
statements
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Separator {
AndAnd,
OrOr,
Always,
Pipe,
}
impl<'os> crate::Shell for Cmd<'os> {
fn name(&self) -> &'static str {
"cmd"
}
fn engine(&self) -> &engine::Engine {
self.os.engine()
}
fn actor(&self) -> engine::ActorId {
self.actor
}
fn environment(&self) -> &os::Environment {
&self.environment
}
fn boot_time(&self) -> Timestamp {
self.os.boot_time()
}
fn hostname(&self) -> String {
self.environment
.get("COMPUTERNAME")
.unwrap_or("vce")
.to_owned()
}
fn cwd(&self) -> &VirtualPath {
&self.cwd
}
fn prompt(&self, _hostname: &str) -> String {
format!("{}>", self.display_path(&self.cwd))
}
fn banner(&self) -> Option<String> {
Some(format!(
"{WINDOWS_VERSION}\n(c) Microsoft Corporation. All rights reserved.\n"
))
}
fn set_terminal_size(&mut self, rows: u16, cols: u16) {
self.environment.set("COLUMNS", cols.to_string());
self.environment.set("LINES", rows.to_string());
}
fn execute(
&mut self,
line: &str,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
self.run_line(line, stdin, stdout, stderr)
}
fn execute_with_terminal(
&mut self,
line: &str,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
_terminal: Option<&mut dyn Terminal>,
) -> ExitStatus {
self.run_line(line, stdin, stdout, stderr)
}
fn take_exit_status(&mut self) -> Option<ExitStatus> {
self.exit_request.take()
}
fn history(&self) -> &[String] {
&self.history
}
fn record_history(&mut self, line: &str) {
if line.trim().is_empty() {
return;
}
self.history.push(line.to_owned());
if self.history.len() > crate::HISTORY_LIMIT {
self.history.remove(0);
}
}
fn needs_continuation(&self, _input: &str) -> bool {
false
}
}
impl<'os> Cmd<'os> {
fn run_line(
&mut self,
line: &str,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let line = line.trim();
if line.is_empty() {
return ExitStatus::SUCCESS;
}
let statements = split_line(line);
let mut last_status = ExitStatus::SUCCESS;
for (separator, stages) in statements {
let should_run = match separator {
None | Some(Separator::Always) => true,
Some(Separator::AndAnd) => last_status.is_success(),
Some(Separator::OrOr) => !last_status.is_success(),
_ => true,
};
if !should_run {
continue;
}
last_status = self.run_pipeline(&stages, stdin, stdout, stderr);
self.environment
.set("errorlevel", last_status.code().to_string());
}
last_status
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Shell as _;
fn session() -> (Box<Cmd<'static>>, &'static Windows) {
let windows = Box::leak(Box::new(
Windows::with_identity(
&os::HostIdentity::new("demo", "demo-host"),
Timestamp::from_nanos(1_000_000),
)
.unwrap(),
));
let actor = windows.authenticate("demo", "demo").unwrap();
let shell = Box::new(Cmd::new(windows, actor, windows.environment().clone()).unwrap());
(shell, windows)
}
fn run(shell: &mut Cmd<'_>, line: &str) -> (ExitStatus, String, String) {
let mut stdin = BytesInput::new(Vec::new());
let mut stdout = BytesOutput::new();
let mut stderr = BytesOutput::new();
let status = shell.execute(line, &mut stdin, &mut stdout, &mut stderr);
(
status,
String::from_utf8_lossy(&stdout.into_bytes()).into_owned(),
String::from_utf8_lossy(&stderr.into_bytes()).into_owned(),
)
}
#[test]
fn echo_prints_and_joins_arguments() {
let (mut shell, _windows) = session();
let (status, out, _) = run(&mut shell, "echo hello world");
assert!(status.is_success());
assert_eq!(out, "hello world\n");
}
#[test]
fn echo_blank_line_and_bare_echo() {
let (mut shell, _windows) = session();
let (_, out, _) = run(&mut shell, "echo.");
assert_eq!(out, "\n");
let (_, out, _) = run(&mut shell, "echo");
assert_eq!(out, "ECHO is on.\n");
}
#[test]
fn percent_variables_expand() {
let (mut shell, _windows) = session();
run(&mut shell, "set GREETING=Hello");
let (_, out, _) = run(&mut shell, "echo %GREETING% world");
assert_eq!(out, "Hello world\n");
let (_, out, _) = run(&mut shell, "echo %greeting%");
assert_eq!(out, "Hello\n", "expansion is case-insensitive");
}
#[test]
fn errorlevel_follows_the_last_command() {
let (mut shell, _windows) = session();
let (_, out, _) = run(&mut shell, "type does-not-exist.txt & echo %errorlevel%");
assert_eq!(out, "1\n");
let (_, out, _) = run(&mut shell, "echo ok & echo %errorlevel%");
assert_eq!(out, "ok\n0\n");
}
#[test]
fn andand_and_oror_conditionals() {
let (mut shell, _windows) = session();
let (status, out, _) = run(&mut shell, "echo one && echo two");
assert!(status.is_success());
assert_eq!(out, "one\ntwo\n");
let (status, out, _) = run(&mut shell, "type nope && echo two || echo fallback");
assert!(status.is_success());
assert!(out.contains("fallback\n"));
assert!(!out.contains("two\n"));
}
#[test]
fn redirection_writes_a_file() {
let (mut shell, _windows) = session();
let (_, _, _) = run(&mut shell, "echo hello > hello.txt");
let (_, out, _) = run(&mut shell, "type hello.txt");
assert_eq!(out, "hello\n");
let (_, _, _) = run(&mut shell, "echo world >> hello.txt");
let (_, out, _) = run(&mut shell, "type hello.txt");
assert_eq!(out, "hello\nworld\n");
}
#[test]
fn cd_and_dir_agree_with_the_filesystem() {
let (mut shell, _windows) = session();
run(&mut shell, "mkdir Work");
let (status, _, _) = run(&mut shell, "cd Work");
assert!(status.is_success());
let (_, out, _) = run(&mut shell, "cd");
assert!(out.contains("Work"), "cd alone prints the cwd: {out}");
}
#[test]
fn pipeline_connects_stdout_to_stdin() {
let (mut shell, _windows) = session();
let (_, out, _) = run(&mut shell, "echo hello | more");
assert_eq!(out, "hello\n");
let (_, out, _) = run(&mut shell, "dir /b | more");
assert!(
out.contains("Desktop"),
"the profile listing flows through the pipeline: {out}"
);
}
#[test]
fn ver_and_exit_work() {
let (mut shell, _windows) = session();
let (_, out, _) = run(&mut shell, "ver");
assert!(out.contains("Microsoft Windows"));
run(&mut shell, "exit 3");
assert_eq!(shell.take_exit_status().map(|s| s.code()), Some(3));
}
#[test]
fn external_commands_resolve() {
let (mut shell, _windows) = session();
let (status, out, _) = run(&mut shell, "hostname");
assert!(status.is_success());
assert!(!out.trim().is_empty());
let (status, out, _) = run(&mut shell, "whoami");
assert!(status.is_success());
assert!(!out.trim().is_empty());
let (status, out, _) = run(&mut shell, "tasklist");
assert!(status.is_success());
assert!(out.contains("hostname") || out.contains("PID"));
}
#[test]
fn unknown_command_reports_cmd_error() {
let (mut shell, _windows) = session();
let (status, _, err) = run(&mut shell, "frobnicate");
assert_eq!(status, ExitStatus::NOT_FOUND);
assert!(err.contains("not recognized as an internal or external command"));
}
}