use std::path::PathBuf;
use std::process::exit;
use clap::Parser;
use itertools::Itertools;
#[derive(Parser, Debug)]
#[clap()]
struct Args {
file: PathBuf,
}
fn main() {
let args: Args = Args::parse();
let edit_script_path = PathBuf::from(std::env::var_os("EDIT_SCRIPT").unwrap());
let edit_script = String::from_utf8(std::fs::read(edit_script_path.clone()).unwrap()).unwrap();
let mut instructions = edit_script.split('\0').collect_vec();
if let Some(pos) = instructions.iter().position(|&i| i == "next invocation\n") {
std::fs::write(edit_script_path, instructions[pos + 1..].join("\0")).unwrap();
instructions.truncate(pos);
}
for instruction in instructions {
let (command, payload) = instruction.split_once('\n').unwrap_or((instruction, ""));
let parts = command.split(' ').collect_vec();
match parts.as_slice() {
[""] => {}
["fail"] => exit(1),
["expect"] => {
let actual = String::from_utf8(std::fs::read(&args.file).unwrap()).unwrap();
if actual != payload {
eprintln!("fake-editor: Unexpected content.\n");
eprintln!("EXPECTED: <{payload}>\nRECEIVED: <{actual}>");
exit(1)
}
}
["write"] => {
std::fs::write(&args.file, payload).unwrap();
}
_ => {
eprintln!("fake-editor: unexpected command: {}", command);
exit(1)
}
}
}
}