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

Add a manual SingleFileExporter #100

Closed
wants to merge 2 commits into from
Closed
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
92 changes: 91 additions & 1 deletion ts-rs/src/export.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{
any::TypeId,
collections::BTreeMap,
collections::{BTreeMap, HashSet},
fmt::Write,
path::{Component, Path, PathBuf},
};
Expand Down Expand Up @@ -161,3 +161,93 @@ where
Some(comps.iter().map(|c| c.as_os_str()).collect())
}
}

#[derive(Debug)]
pub struct MissingDependenciesError {
dependencies: Vec<String>,
}

impl std::fmt::Display for MissingDependenciesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Missing required types: {}",
self.dependencies.join(", ")
)
}
}

impl std::error::Error for MissingDependenciesError {}

/// Allows exporting multiple types to a single file.
pub struct SingleFileExporter {
required_type_ids: HashSet<(TypeId, String)>,
added_types: HashSet<TypeId>,
buffer: String,
}

impl SingleFileExporter {
pub fn new(with_codegen_warning: bool) -> Self {
let buffer = if with_codegen_warning {
NOTE.to_string()
} else {
String::new()
};
Comment on lines +191 to +195
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@NyxCode should the codegen warning be optional?


Self {
required_type_ids: HashSet::new(),
added_types: HashSet::new(),
buffer,
}
}

pub fn add_type<T: TS + 'static>(&mut self) {
let id = TypeId::of::<T>();
if self.added_types.contains(&id) {
return;
}

if !self.buffer.is_empty() {
self.buffer.push('\n');
}
generate_decl::<T>(&mut self.buffer);
self.buffer.push('\n');
self.added_types.insert(id);

for dep in T::dependencies() {
self.required_type_ids
.insert((dep.type_id, dep.ts_name.clone()));
}
}

pub fn and<T: TS + 'static>(mut self) -> Self {
self.add_type::<T>();
self
}

/// Finalize the export.
///
/// Returns the generated typescritp code on success, or an error if any
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo in "typescript"

/// required type dependencies were not added.
pub fn finish(self) -> Result<String, MissingDependenciesError> {
let missing: Vec<String> = self
.required_type_ids
.into_iter()
.filter_map(|(id, name)| {
if self.added_types.contains(&id) {
None
} else {
Some(name)
}
})
.collect();

if !missing.is_empty() {
Err(MissingDependenciesError {
dependencies: missing,
})
} else {
Ok(self.buffer)
}
}
}
2 changes: 1 addition & 1 deletion ts-rs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ use std::{

pub use ts_rs_macros::TS;

pub use crate::export::ExportError;
pub use crate::export::{ExportError, MissingDependenciesError, SingleFileExporter};

#[cfg(feature = "chrono-impl")]
mod chrono;
Expand Down
30 changes: 30 additions & 0 deletions ts-rs/tests/singlefile.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#![allow(dead_code)]

use ts_rs::{SingleFileExporter, TS};

#[derive(TS)]
struct Alpha {
b: Beta,
}

#[derive(TS)]
struct Beta {
x: bool,
}

#[test]
fn test_singlefile() {
let out = SingleFileExporter::new(false)
.and::<Alpha>()
.and::<Beta>()
.finish()
.unwrap();

assert_eq!(
out,
r#"export type Alpha = { b: Beta, }

export type Beta = { x: boolean, }
"#
);
}
Loading