fixed the inclusion errors

Dieser Commit ist enthalten in:
Sebastian Tobie 2024-12-02 21:18:42 +01:00
Ursprung 352fabd0b1
Commit eba9f1b443
2 geänderte Dateien mit 56 neuen und 17 gelöschten Zeilen

Datei anzeigen

@ -1,3 +1,5 @@
use std::fs;
use proc_macro::TokenStream; use proc_macro::TokenStream;
use quote::quote; use quote::quote;
use syn::{ use syn::{
@ -7,6 +9,10 @@ use syn::{
}; };
use syn::{parse, LitInt, Result}; use syn::{parse, LitInt, Result};
const DATA_DIR: &str = "data";
const EXAMPLE_DIR: &str = "examples";
#[derive(Debug, Clone)]
struct IncludeData { struct IncludeData {
year: String, year: String,
day: String, day: String,
@ -63,20 +69,29 @@ impl Parse for IncludeData {
} }
} }
fn get_stream(dir: &str, data: Result<IncludeData>) -> TokenStream { fn canonicalize(dir: &str, input: Result<IncludeData>) -> Option<String> {
match data { let pathname = match input {
Ok(id) => { Ok(id) => Some(format!("{}/{}/{}.txt", dir, id.year, id.day)),
let path = format!("../../../{}/{}/{}.txt", dir, id.year, id.day); Err(_) => None,
quote! { };
static DATA: &str = include_str!(#path); if let Some(p) = pathname {
match fs::canonicalize(p.clone()) {
Ok(canon) => {
if canon.is_file() {
Some(canon.to_str().unwrap().to_string())
} else {
println!("ERROR: {:?} is not a file", canon);
None
}
}
Err(err) => {
println!("ERROR: {} does not exist: {}", p, err);
None
} }
} }
Err(_)=> { } else {
quote! { None
static DATA: &str = ""; }
}
}
}.into()
} }
/// includes Data from Advent of code /// includes Data from Advent of code
@ -93,10 +108,33 @@ fn get_stream(dir: &str, data: Result<IncludeData>) -> TokenStream {
/// ``` /// ```
#[proc_macro] #[proc_macro]
pub fn include_data(data: TokenStream) -> TokenStream { pub fn include_data(data: TokenStream) -> TokenStream {
get_stream("data", parse::<IncludeData>(data)) let input = parse::<IncludeData>(data);
let mut path = canonicalize(DATA_DIR, input.clone());
if path.is_none() {
path = canonicalize(EXAMPLE_DIR, input)
}
match path {
Some(p) => quote! {
static DATA: &str = include_str!(#p);
}
.into(),
None => quote! {
static DATA: &str = "";
}
.into(),
}
} }
#[proc_macro] #[proc_macro]
pub fn include_example(data: TokenStream)->TokenStream { pub fn include_example(data: TokenStream) -> TokenStream {
get_stream("examples", parse::<IncludeData>(data)) match canonicalize(EXAMPLE_DIR, parse::<IncludeData>(data)) {
} Some(p) => quote! {
static DATA: &str = include_str!(#p);
}
.into(),
None => quote! {
static DATA: &str = "";
}
.into(),
}
}

Datei anzeigen

@ -1,5 +1,6 @@
use advent_of_code::strings::{parsenumber, splitspace}; use advent_of_code::strings::{parsenumber, splitspace};
use adventofcode_macros::include_data; #[allow(unused_imports)]
use adventofcode_macros::{include_data, include_example};
include_data!(2024 01); include_data!(2024 01);