File size: 1,385 Bytes
fda8632
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
use super::approval::{Approval, DENIED_WRITE};
use super::web_tools::io_detail;
use std::fs::File;
use std::io::Write;
use std::os::unix::ffi::OsStrExt;

pub(crate) const WRITE: &str = "write";

pub(crate) fn write_result(path: Option<&str>, content: Option<&str>) -> Vec<u8> {
    write_result_with(path, content, &mut Approval::NonInteractive)
}

pub(crate) fn write_result_with(
    path: Option<&str>,
    content: Option<&str>,
    approval: &mut Approval<'_>,
) -> Vec<u8> {
    let Some(path) = path.filter(|path| !path.is_empty()) else {
        return b"Tool error: write requires path\n".to_vec();
    };
    let Some(content) = content else {
        return b"Tool error: write requires content\n".to_vec();
    };
    if !approval.allow_write(path) {
        return DENIED_WRITE.to_vec();
    }
    let os_path = std::ffi::OsStr::from_bytes(path.as_bytes());
    let mut file = match File::create(os_path) {
        Ok(file) => file,
        Err(error) => {
            return format!("Tool error: open for write failed: {}\n", io_detail(&error))
                .into_bytes();
        }
    };
    if let Err(error) = file
        .write_all(content.as_bytes())
        .and_then(|_| file.flush())
    {
        return format!("Tool error: write failed: {}\n", io_detail(&error)).into_bytes();
    }
    format!("Wrote {} bytes to {path}\n", content.len()).into_bytes()
}