utf8-forge 0.1.0

A focused, idempotent, bidirectional charset transcoder for source trees. Default output: UTF-8 without BOM.
Documentation
//! Optional remote download (`DESIGN.md §8`).
//!
//! Compiled only with the `remote` feature (default). Reuses the exact same
//! `detect()` / `transcode()` pipeline as the local path — only the source of
//! `raw_bytes` changes. Downloaded content is treated as untrusted text:
//! strict decoding rejects malformed byte sequences, no shell is executed,
//! no recursive link following.

use std::path::PathBuf;
use std::time::Duration;

use crate::error::ForgeError;

/// Fetch `url` into memory, capped by `max_size`.
///
/// `Content-Length` is checked before reading when present; the buffered
/// body is checked again after reading (covers chunked responses without a
/// declared length). Redirects are limited to 5; total timeout is 120 s,
/// connect timeout 30 s (`DESIGN.md §8.4`).
pub fn fetch_bytes(url: &str, max_size: u64) -> Result<Vec<u8>, ForgeError> {
    let client = reqwest::blocking::Client::builder()
        .connect_timeout(Duration::from_secs(30))
        .timeout(Duration::from_secs(120))
        .redirect(reqwest::redirect::Policy::limited(5))
        .build()
        .map_err(|e| ForgeError::Fetch(format!("client build failed: {e}")))?;

    let resp = client
        .get(url)
        .send()
        .map_err(|e| ForgeError::Fetch(format!("request failed: {e}")))?
        .error_for_status()
        .map_err(|e| ForgeError::Fetch(format!("http status: {e}")))?;

    if let Some(len) = resp.content_length() {
        if len > max_size {
            return Err(ForgeError::TooLarge {
                size: len,
                max: max_size,
            });
        }
    }

    let body = resp
        .bytes()
        .map_err(|e| ForgeError::Fetch(format!("read body failed: {e}")))?;
    let len = body.len() as u64;
    if len > max_size {
        return Err(ForgeError::TooLarge {
            size: len,
            max: max_size,
        });
    }
    Ok(body.to_vec())
}

/// Derive the output path from the URL when `--output` is omitted
/// (`DESIGN.md §8.2`):
///
/// - last non-empty path segment with an extension is kept verbatim
///   (`.../legacy.cpp` → `legacy.cpp`);
/// - a segment without an extension gets `.utf8` appended (`.../foo` → `foo.utf8`);
/// - no usable segment → `download.utf8`.
pub fn derive_output_path(url: &str) -> PathBuf {
    let segment = url::Url::parse(url)
        .ok()
        .and_then(|u| {
            u.path_segments()?
                .next_back()
                .map(str::to_owned)
                .filter(|s| !s.is_empty())
        });

    match segment {
        Some(seg) if has_extension(&seg) => PathBuf::from(seg),
        Some(seg) => PathBuf::from(format!("{seg}.utf8")),
        None => PathBuf::from("download.utf8"),
    }
}

/// True when the last URL segment looks like a filename with an extension.
fn has_extension(segment: &str) -> bool {
    std::path::Path::new(segment)
        .extension()
        .map(|e| !e.is_empty())
        .unwrap_or(false)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn derive_keeps_extensioned_segments() {
        assert_eq!(
            derive_output_path("https://example.com/data/legacy.cpp"),
            PathBuf::from("legacy.cpp")
        );
    }

    #[test]
    fn derive_appends_utf8_without_extension() {
        assert_eq!(
            derive_output_path("https://example.com/foo"),
            PathBuf::from("foo.utf8")
        );
    }

    #[test]
    fn derive_falls_back_when_no_segment() {
        assert_eq!(
            derive_output_path("https://example.com/"),
            PathBuf::from("download.utf8")
        );
        assert_eq!(
            derive_output_path("not a url"),
            PathBuf::from("download.utf8")
        );
    }

    #[test]
    fn derive_ignores_query_string() {
        assert_eq!(
            derive_output_path("https://example.com/a.cpp?raw=1"),
            PathBuf::from("a.cpp")
        );
    }

    #[test]
    fn derive_treats_trailing_dot_as_missing_extension() {
        assert_eq!(
            derive_output_path("https://example.com/foo."),
            PathBuf::from("foo..utf8")
        );
    }
}