bincode_typescript/
lib.rs1use askama::Template;
2use enums::EnumDeclaration;
3use std::{
4 error::Error,
5 fs::{self},
6 path::Path,
7};
8use structs::StructDeclaration;
9use syn::{
10 visit::{self, Visit},
11 ItemEnum, ItemStruct,
12};
13
14mod enums;
15mod structs;
16mod types;
17
18const NAME: &str = env!("CARGO_PKG_NAME");
19const VERSION: &str = env!("CARGO_PKG_VERSION");
20
21#[derive(Clone, Debug, Template)]
22#[template(path = "module.ts.j2", escape = "txt")]
23struct CodeVisitor {
24 pub pkg_name: String,
25 pub pkg_version: String,
26 support_buffer: bool,
27 pub structs: Vec<StructDeclaration>,
28 pub enums: Vec<EnumDeclaration>,
29}
30
31impl CodeVisitor {
32 pub fn new(support_buffer: bool) -> Self {
33 CodeVisitor {
34 pkg_name: NAME.to_string(),
35 pkg_version: VERSION.to_string(),
36 support_buffer,
37 structs: Default::default(),
38 enums: Default::default(),
39 }
40 }
41}
42
43impl<'ast> Visit<'ast> for CodeVisitor {
44 fn visit_item_struct(&mut self, node: &'ast ItemStruct) {
45 self.structs.push(node.clone().into());
46 visit::visit_item_struct(self, node);
47 }
48
49 fn visit_item_enum(&mut self, node: &'ast ItemEnum) {
50 self.enums.push(node.clone().into());
51 visit::visit_item_enum(self, node);
52 }
53}
54
55pub fn from_string(input: &str, buffer_support: bool) -> Result<String, Box<dyn Error>> {
56 let ast = syn::parse_file(input)?;
57 let mut enum_visit = CodeVisitor::new(buffer_support);
58 enum_visit.visit_file(&ast);
59
60 Ok(enum_visit.render()?)
61}
62
63pub fn from_file<P1: AsRef<Path>, P2: AsRef<Path>>(
64 input: P1,
65 output: P2,
66 buffer_support: bool,
67) -> Result<(), Box<dyn Error>> {
68 fs::create_dir_all(&output.as_ref().parent().unwrap())?;
69 let rust = fs::read_to_string(input)?;
70 let typescript = from_string(&rust, buffer_support)?;
71 fs::write(output, typescript)?;
72
73 Ok(())
74}