| 1 |
use gf_metadata::AxisProto; |
| 2 |
use proc_macro2::TokenStream; |
| 3 |
use quote::quote; |
| 4 |
use std::{ |
| 5 |
env, |
| 6 |
fs::File, |
| 7 |
io::{BufWriter, Write}, |
| 8 |
path::Path, |
| 9 |
}; |
| 10 |
|
| 11 |
fn main() { |
| 12 |
let path = Path::new(&env::var("OUT_DIR").unwrap()).join("data.rs"); |
| 13 |
let mut file = BufWriter::new(File::create(path).unwrap()); |
| 14 |
let mut output = quote! { use std::collections::BTreeMap; use std::sync::LazyLock; }; |
| 15 |
|
| 16 |
output.extend(serialize_a_structure( |
| 17 |
"Lib/axisregistry/data/*.textproto", |
| 18 |
"AXES", |
| 19 |
)); |
| 20 |
|
| 21 |
// let formatted = output.to_string(); |
| 22 |
|
| 23 |
let abstract_file: syn::File = syn::parse2(output).expect("Could not parse output"); |
| 24 |
let formatted = prettyplease::unparse(&abstract_file); |
| 25 |
file.write_all(formatted.as_bytes()) |
| 26 |
.expect("Could not write to file"); |
| 27 |
} |
| 28 |
|
| 29 |
fn serialize_a_structure(pathglob: &str, output_variable: &str) -> TokenStream { |
| 30 |
let files: Vec<std::path::PathBuf> = glob::glob(pathglob) |
| 31 |
.expect("Failed to read glob pattern") |
| 32 |
.flatten() |
| 33 |
.collect(); |
| 34 |
let variable: TokenStream = output_variable.parse().unwrap(); |
| 35 |
let mut gobbets = vec![]; |
| 36 |
let mut names = vec![]; |
| 37 |
let mut tags = vec![]; |
| 38 |
for file in files.into_iter() { |
| 39 |
let (gobbet, name, tag) = serialize_file(file); |
| 40 |
gobbets.push(gobbet); |
| 41 |
names.push(name); |
| 42 |
tags.push(tag); |
| 43 |
} |
| 44 |
quote! { |
| 45 |
#(#gobbets)* |
| 46 |
#[doc = "A map of all the Axis objects"] |
| 47 |
pub static #variable: LazyLock<BTreeMap<String, Box<AxisProto>>> = LazyLock::new(|| { |
| 48 |
let mut m = BTreeMap::new(); |
| 49 |
#( |
| 50 |
let proto: AxisProto = AxisProto::parse_from_str(#names).expect("Could not parse JSON"); |
| 51 |
m.insert(#tags.to_string(), Box::new(proto)); |
| 52 |
)* |
| 53 |
m |
| 54 |
}); |
| 55 |
} |
| 56 |
} |
| 57 |
fn serialize_file(path: std::path::PathBuf) -> (TokenStream, TokenStream, String) { |
| 58 |
let contents = std::fs::read_to_string(&path).expect("Could not read file"); |
| 59 |
let proto: AxisProto = AxisProto::parse_from_str(&contents) |
| 60 |
.unwrap_or_else(|_| panic!("Could not parse proto {}", path.display())); |
| 61 |
let name: TokenStream = format!("AXIS_{}", proto.tag().to_ascii_uppercase()) |
| 62 |
.parse() |
| 63 |
.unwrap(); |
| 64 |
// Resolve absolute path here |
| 65 |
let path = std::fs::canonicalize(path).unwrap(); |
| 66 |
let path_as_string = path.to_str().unwrap(); |
| 67 |
let tag: String = proto.tag().to_string().parse().unwrap(); |
| 68 |
let include_gobbet = quote! { |
| 69 |
const #name: &str = include_str!(#path_as_string); |
| 70 |
}; |
| 71 |
(include_gobbet, name, tag) |
| 72 |
} |