Skip to content

Commit 18d34e8

Browse files
authored
Merge pull request #3 from spindle-app/feature/add_custom_use_and_derive
Add custom use and derive for Rust
2 parents b7c58fc + eece263 commit 18d34e8

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

crates/target_rust/src/lib.rs

+39-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use jtd_codegen::error::Error;
12
use jtd_codegen::target::{self, inflect, metadata};
23
use jtd_codegen::Result;
34
use lazy_static::lazy_static;
@@ -236,15 +237,52 @@ impl jtd_codegen::target::Target for Target {
236237
return Ok(Some(s.into()));
237238
}
238239

240+
let mut derives = vec!["Serialize", "Deserialize"];
241+
242+
if let Some(s) = metadata.get("rustCustomDerive").and_then(|v| v.as_str()) {
243+
derives.extend(s.split(","));
244+
}
245+
239246
state
240247
.imports
241248
.entry("serde".into())
242249
.or_default()
243250
.extend(vec!["Deserialize".to_owned(), "Serialize".to_owned()]);
244251

252+
let mut custom_use = Vec::<&str>::new();
253+
if let Some(s) = metadata.get("rustCustomUse").and_then(|v| v.as_str()) {
254+
custom_use.extend(s.split(";"));
255+
}
256+
for cu in custom_use {
257+
// custom::path::{import,export} or custom::path::single
258+
let mut use_imports = Vec::<&str>::new();
259+
let mut path_parts = cu.split("::").collect::<Vec<&str>>();
260+
let mut last_part = path_parts.pop().unwrap();
261+
// If there are no path_parts or the last part was "", panic!
262+
if path_parts.len() < 1 || last_part.trim().len() < 1 {
263+
return Err(Error::Io(std::io::Error::new(
264+
std::io::ErrorKind::Other,
265+
format!("Invalid custom use statement: {:?}", cu),
266+
)));
267+
}
268+
if last_part.starts_with('{') {
269+
// Strip the first/last chars and split
270+
last_part = &last_part[1..last_part.len() - 1];
271+
use_imports.extend(last_part.split(","))
272+
} else {
273+
// No, just push it into the imports list
274+
use_imports.push(last_part);
275+
}
276+
state
277+
.imports
278+
.entry(path_parts.join("::").into())
279+
.or_default()
280+
.extend(use_imports.drain(..).map(|i| i.trim().to_owned()));
281+
}
282+
245283
writeln!(out)?;
246284
write!(out, "{}", description(&metadata, 0))?;
247-
writeln!(out, "#[derive(Serialize, Deserialize)]")?;
285+
writeln!(out, "#[derive({})]", derives.join(", "))?;
248286

249287
if fields.is_empty() {
250288
writeln!(out, "pub struct {} {{}}", name)?;

0 commit comments

Comments
 (0)