use tinysandbox::sandbox::{CommandContext, CommandResult, Sandbox};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
#[tokio::main]
async fn main() {
let sandbox = Sandbox::builder()
.command("shout", |mut ctx: CommandContext| async move {
let mut input = String::new();
if ctx.stdin.read_to_string(&mut input).await.is_err() {
return CommandResult::failure();
}
let output = input.to_uppercase();
match ctx.args.first() {
Some(path) => {
if let Err(err) = ctx.fs.write_file(path, output.as_bytes(), false).await {
let _ = ctx
.stderr
.write_all(format!("shout: {path}: {err:?}\n").as_bytes())
.await;
return CommandResult::failure();
}
}
None => {
let _ = ctx.stdout.write_all(output.as_bytes()).await;
}
}
CommandResult::success()
})
.build();
let result = sandbox.exec("which shout && ls /bin | grep shout").await;
print!("{}", result.stdout);
let result = sandbox.exec("echo make some noise | shout").await;
assert_eq!(result.stdout, "MAKE SOME NOISE\n");
print!("{}", result.stdout);
sandbox.exec("echo quiet words | shout /loud.txt").await;
let result = sandbox.exec("cat /loud.txt").await;
assert_eq!(result.stdout, "QUIET WORDS\n");
print!("{}", result.stdout);
}