1#![doc = include_str!("../README.md")]
23use std::path::Path;
4use std::process::Command;
5use std::{env, fs};
67use anyhow::Context;
8use proc_macro2::{Ident, Span, TokenStream};
910pub fn write_generated_file(content: TokenStream, out_file: &str) -> anyhow::Result<()> {
11let out_dir = env::var_os("OUT_DIR").context("failed to get OUT_DIR env var")?;
12let path = Path::new(&out_dir).join(out_file);
13let code = content.to_string();
1415 fs::write(&path, code)?;
1617// Try to format the output for debugging purposes.
18 // Doesn't matter if rustfmt is unavailable.
19let _ = Command::new("rustfmt").arg(path).output();
2021Ok(())
22}
2324/// Parses a [`proc_macro2::Ident`] from a `str`. Rust keywords are prepended
25/// with underscores to make them valid identifiers.
26pub fn ident<I: AsRef<str>>(s: I) -> Ident {
27let s = s.as_ref().trim();
2829// Parse the ident from a str. If the string is a Rust keyword, stick an
30 // underscore in front.
31syn::parse_str::<Ident>(s)
32 .unwrap_or_else(|_| Ident::new(format!("_{s}").as_str(), Span::call_site()))
33}
3435#[track_caller]
36pub fn rerun_if_changed<const N: usize>(files: [&str; N]) {
37for file in files {
38assert!(
39 Path::new(file).exists(),
40"File \"{file}\" does not exist. Did you forget to update the path?"
41);
4243println!("cargo:rerun-if-changed={file}");
44 }
45}