I’m stuck on Stage #JV1. (Redirect Stdout)
Here are my logs:
[your-program] $ echo 'Hello James' 1> /tmp/rat/cow.md
[your-program] $ cat /tmp/rat/cow.md
[your-program] 'Hello James'
[tester::#JV1] ^ Line does not match expected value.
[tester::#JV1] Expected: "Hello James"
[tester::#JV1] Received: "'Hello James'"
And here’s a snippet of my code:
use std::{fs::{self, File}, io::{self, Write}, path::Path};
enum Command<'a> {
Builtin {
command: Builtin<'a>,
stdout: Option<&'a Path>,
},
// other commands
}
enum Builtin<'a> {
Echo(&'a str),
// other builtins
}
trait Eval<'a> {
fn eval(self, stdout: Option<&'a Path>) -> Result<(), io::Error>;
}
fn main() -> Result<(), io::Error> {
let mut input = String::new();
loop {
// display prompt
io::stdin().read_line(&mut input)?;
match Command::from(input.as_str()) {
Command::Builtin { command, stdout } => command.eval(stdout)?,
// other commands
}
input.clear();
}
Ok(())
}
impl<'a> From<&'a str> for Command<'a> {
fn from(input: &'a str) -> Self {
let (cmd, args) = input.split_once(" ").unwrap_or((input, ""));
let (args, stdout) = match args.trim().split_once("1>") {
Some((args, stdout)) => (args, Some(Path::new(stdout.trim()))),
None => match args.split_once(">") {
Some((args, stdout)) => (args, Some(Path::new(stdout.trim()))),
None => (args, None),
},
};
match cmd.trim() {
"echo" => Command::Builtin {
command: Builtin::Echo(args),
stdout,
},
// other commands
}
}
}
impl<'a> Eval<'a> for Builtin<'a> {
fn eval(self, stdout: Option<&'a Path>) -> Result<(), io::Error> {
let mut output_stdout: io::Stdout;
let mut output_file: File;
let stdout: &mut dyn Write = match stdout {
Some(path) => {
if let Some(dir_path) = path.parent() {
fs::create_dir_all(dir_path)?;
}
output_file = File::create(path)?;
&mut output_file
}
None => {
output_stdout = io::stdout();
&mut output_stdout
}
};
match self {
Builtin::Echo(args) => writeln!(stdout, "{}", args.trim())?,
// other builtins
}
Ok(())
}
}
It seems like echo should be swallowing the quotes (according to this test), but nothing in the earlier stages has required it. If my echo implementation passed the earlier tests, including the ones for stage #IZ3 (implementing echo), I should hope it’s not the problem now. If redirecting output should strip quotes, this should be explained in #JV1.
Published to Github here.