obelix 0.2.0

Obélix is a tool to reduce Rust source files to produce MVEs
Documentation
use quote::ToTokens;
use std::io::Read;

#[test]
fn errors() {
    let files =
        std::fs::read_dir("./tests/errors-resources").expect("Could not iterate resource folder");

    let results = files
        .map(|file| {
            let file = file.expect("Could not read directory entry");
            let file = file.path();

            println!("Testing {}", file.display());
            test_one(&file)
        })
        .filter_map(|r| r.err())
        .collect::<Vec<_>>();

    if !results.is_empty() {
        panic!("Error on: {}", results.join(", "));
    }
}

#[test]
#[ignore]
/// Convenient way to run a single test
fn error() {
    if let Err(e) = test_one(&"./tests/errors-resources/so-62355091_in.rs") {
        panic!("Error: {:?}", e);
    }
}

fn test_one<P: AsRef<std::path::Path>>(file: P) -> Result<(), String> {
    let file = file.as_ref();
    let mut file_name = file
        .file_name()
        .expect("Invalid path")
        .to_str()
        .expect("Invalid path")
        .rsplitn(2, '_');

    let (long_extension, file_name) = (
        file_name.next().expect("Invalid path"),
        file_name.next().expect("Invalid path"),
    );

    match long_extension {
        "in.rs" => (),
        "out.rs" => return Ok(()),
        "result.rs" => return Ok(()),
        e => panic!("Invalid extension `{}`", e),
    }

    let expected = {
        let mut expected = String::new();
        let mut output_file =
            std::fs::File::open(file.with_file_name(format!("{}_out.rs", file_name)))
                .expect("Could not read file");
        output_file
            .read_to_string(&mut expected)
            .expect("Could not read file content");

        syn::parse_str::<syn::File>(&expected).expect("Could not parse expected file")
    };

    let buffer = {
        let mut buffer = String::new();
        let mut file = std::fs::File::open(file).expect("Could not read file");
        file.read_to_string(&mut buffer)
            .expect("Could not read file content");

        buffer
    };

    let mut parsed_file = syn::parse_str::<syn::File>(&buffer).expect("Could not parse file");

    obelix::simplify(&mut parsed_file);

    if expected == parsed_file {
        Ok(())
    } else {
        use std::io::Write;

        println!("{:?}", expected);
        println!("{:?}", parsed_file);
        let mut output_file =
            std::fs::File::create(file.with_file_name(format!("{}_result.rs", file_name)))
                .expect("Could not create file");

        output_file
            .write(parsed_file.into_token_stream().to_string().as_bytes())
            .expect("Could not write file");

        Err(file_name.to_string())
    }
}