magi-code 0.63.4

Repository-aware CLI coding agent for terminal work
Documentation
use std::{fs::File, io::Read, path::Path};

pub(crate) const DEFAULT_BOUNDED_BODY_MAX_BYTES: u64 = 2 * 1024 * 1024;

pub(crate) fn read_bounded_response_text(
    response: reqwest::blocking::Response,
    max_bytes: u64,
) -> anyhow::Result<String> {
    let mut bounded = response.take(max_bytes + 1);
    let mut text = String::new();
    bounded.read_to_string(&mut text)?;
    if text.len() as u64 > max_bytes {
        anyhow::bail!("response exceeded {max_bytes} bytes");
    }
    Ok(text)
}

pub(crate) fn read_bounded_file_to_string(
    path: impl AsRef<Path>,
    max_bytes: u64,
) -> Option<String> {
    let mut bounded = File::open(path).ok()?.take(max_bytes + 1);
    let mut text = String::new();
    bounded.read_to_string(&mut text).ok()?;
    if text.len() as u64 > max_bytes {
        return None;
    }
    Some(text)
}