Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use include_str! to trigger a rebuild when the input spec is modified #16

Merged
merged 2 commits into from
Nov 17, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 25 additions & 24 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

40 changes: 24 additions & 16 deletions progenitor-macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::path::Path;
use openapiv3::OpenAPI;
use proc_macro::TokenStream;
use progenitor_impl::Generator;
use quote::ToTokens;
use quote::{quote, ToTokens};
use syn::{
parse::{Parse, ParseStream},
ExprClosure, LitStr, Token,
Expand Down Expand Up @@ -90,31 +90,39 @@ fn do_generate_api(item: TokenStream) -> Result<TokenStream, syn::Error> {
);

let path = dir.join(file.value());
let path_str = path.to_string_lossy();

let content = std::fs::read_to_string(&path).map_err(|e| {
syn::Error::new(
file.span(),
format!("couldn't read file {}: {}", file.value(), e.to_string()),
)
})?;

let spec = serde_json::from_str::<OpenAPI>(&content).map_err(|e| {
syn::Error::new(
file.span(),
format!("failed to parse {}: {}", file.value(), e.to_string()),
)
})?;
let spec: OpenAPI =
serde_json::from_reader(std::fs::File::open(&path).map_err(|e| {
syn::Error::new(
file.span(),
format!("couldn't read file {}: {}", path_str, e.to_string()),
)
})?)
.map_err(|e| {
syn::Error::new(
file.span(),
format!("failed to parse {}: {}", path_str, e.to_string()),
)
})?;

let mut builder = Generator::new();
inner.map(|inner_type| builder.with_inner_type(inner_type));
pre.map(|pre_hook| builder.with_pre_hook(pre_hook));
post.map(|post_hook| builder.with_post_hook(post_hook));
let ret = builder.generate_tokens(&spec).map_err(|e| {
let code = builder.generate_tokens(&spec).map_err(|e| {
syn::Error::new(
file.span(),
format!("generation error for {}: {}", file.value(), e.to_string()),
)
})?;

Ok(ret.into())
let output = quote! {
#code

// Force a rebuild when the given file is modified.
const _: &str = include_str!(#path_str);
};

Ok(output.into())
}