valence_build_utils/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use std::path::Path;
4use std::process::Command;
5use std::{env, fs};
6
7use anyhow::Context;
8use proc_macro2::{Ident, Span, TokenStream};
9
10pub fn write_generated_file(content: TokenStream, out_file: &str) -> anyhow::Result<()> {
11    let out_dir = env::var_os("OUT_DIR").context("failed to get OUT_DIR env var")?;
12    let path = Path::new(&out_dir).join(out_file);
13    let code = content.to_string();
14
15    fs::write(&path, code)?;
16
17    // Try to format the output for debugging purposes.
18    // Doesn't matter if rustfmt is unavailable.
19    let _ = Command::new("rustfmt").arg(path).output();
20
21    Ok(())
22}
23
24/// 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 {
27    let s = s.as_ref().trim();
28
29    // Parse the ident from a str. If the string is a Rust keyword, stick an
30    // underscore in front.
31    syn::parse_str::<Ident>(s)
32        .unwrap_or_else(|_| Ident::new(format!("_{s}").as_str(), Span::call_site()))
33}
34
35#[track_caller]
36pub fn rerun_if_changed<const N: usize>(files: [&str; N]) {
37    for file in files {
38        assert!(
39            Path::new(file).exists(),
40            "File \"{file}\" does not exist. Did you forget to update the path?"
41        );
42
43        println!("cargo:rerun-if-changed={file}");
44    }
45}