diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 39b0e76..10fb9a0 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -18,7 +18,8 @@ jobs: working-directory: e2e/dependencies/consumer run: | TS_RS_EXPORT_DIR=custom-bindings cargo t - tsc custom-bindings/* --noEmit --noUnusedLocals --strict + shopt -s globstar + tsc custom-bindings/**/*.ts --noEmit --noUnusedLocals --strict e2e-workspace: name: Run 'workspace' end-to-end test runs-on: ubuntu-latest @@ -36,7 +37,8 @@ jobs: working-directory: e2e/workspace run: | TS_RS_EXPORT_DIR=custom-bindings cargo t - tsc parent/custom-bindings/* --noEmit --noUnusedLocals --strict + shopt -s globstar + tsc parent/custom-bindings/**/*.ts --noEmit --noUnusedLocals --strict e2e-example: name: End-to-end test example runs-on: ubuntu-latest @@ -54,7 +56,8 @@ jobs: working-directory: example run: | TS_RS_EXPORT_DIR=custom-bindings cargo t - tsc custom-bindings/* --noEmit --noUnusedLocals --strict + shopt -s globstar + tsc custom-bindings/**/*.ts --noEmit --noUnusedLocals --strict readme-up-to-date: name: Check that README.md is up-to-date @@ -88,3 +91,8 @@ jobs: cargo test --all-features shopt -s globstar tsc ts-rs/tests-out/**/*.ts --noEmit --noUnusedLocals --strict + - name: test with export env + run: | + TS_RS_EXPORT_DIR=output cargo test --no-default-features + shopt -s globstar + tsc ts-rs/output/tests-out/**/*.ts --noEmit --noUnusedLocals --strict diff --git a/macros/src/lib.rs b/macros/src/lib.rs index afb24c2..df1aa7b 100644 --- a/macros/src/lib.rs +++ b/macros/src/lib.rs @@ -30,26 +30,54 @@ struct DerivedTS { impl DerivedTS { fn into_impl(mut self, rust_ty: Ident, generics: Generics) -> TokenStream { - let mut get_export_to = quote! {}; - let export_to = match &self.export_to { - Some(dirname) if dirname.ends_with('/') => { - format!("{}{}.ts", dirname, self.ts_name) - } - Some(filename) => filename.clone(), - None => { - get_export_to = quote! { - fn get_export_to() -> Option { - ts_rs::__private::get_export_to_path::() - } - }; - format!("bindings/{}.ts", self.ts_name) - } - }; - let export = self .export .then(|| self.generate_export_test(&rust_ty, &generics)); + let export_dir = std::env::var("TS_RS_EXPORT_DIR").ok(); + let export_to = { + let path = match self.export_to.as_deref() { + Some(dirname) if dirname.ends_with('/') => { + export_dir + .map_or_else( + || format!("{}{}.ts", dirname, self.ts_name), + |ts_rs_dir| format!( + "{}/{}{}.ts", + ts_rs_dir.trim_end_matches('/'), + dirname, + self.ts_name, + ) + ) + }, + Some(filename) => { + export_dir + .map_or_else( + || filename.to_owned(), + |ts_rs_dir| format!( + "{}/{}", + ts_rs_dir.trim_end_matches('/'), + filename, + ), + ) + }, + None => { + export_dir + .map_or_else( + || format!("bindings/{}.ts", self.ts_name), + |ts_rs_dir| format!( + "{}/{}.ts", + ts_rs_dir.trim_end_matches('/'), + self.ts_name, + ), + ) + }, + }; + + quote! { + const EXPORT_TO: Option<&'static str> = Some(#path); + } + }; + let docs = match &*self.docs { "" => None, docs => Some(quote!(const DOCS: Option<&'static str> = Some(#docs);)), @@ -67,13 +95,12 @@ impl DerivedTS { quote! { #impl_start { #assoc_type - const EXPORT_TO: Option<&'static str> = Some(#export_to); + #export_to fn ident() -> String { #ident.to_owned() } - #get_export_to #docs #name #decl diff --git a/ts-rs/src/export.rs b/ts-rs/src/export.rs index eeb6078..de37373 100644 --- a/ts-rs/src/export.rs +++ b/ts-rs/src/export.rs @@ -5,7 +5,7 @@ use std::{ collections::BTreeMap, fmt::Write, path::{Component, Path, PathBuf}, - sync::{Mutex, OnceLock}, + sync::Mutex, }; use thiserror::Error; @@ -124,30 +124,6 @@ pub(crate) fn export_type_to>( Ok(()) } -#[doc(hidden)] -pub mod __private { - use super::*; - - const EXPORT_DIR_ENV_VAR: &str = "TS_RS_EXPORT_DIR"; - fn provided_default_dir() -> Option<&'static str> { - static EXPORT_TO: OnceLock> = OnceLock::new(); - EXPORT_TO - .get_or_init(|| std::env::var(EXPORT_DIR_ENV_VAR).ok()) - .as_deref() - } - - /// Returns the path to where `T` should be exported using the `TS_RS_EXPORT_DIR` environment variable. - /// - /// This should only be used by the TS derive macro; the `get_export_to` trait method should not - /// be overridden if the `#[ts(export_to = ..)]` attribute exists. - pub fn get_export_to_path() -> Option { - provided_default_dir().map_or_else( - || T::EXPORT_TO.map(ToString::to_string), - |path| Some(format!("{path}/{}.ts", T::ident())), - ) - } -} - /// Returns the generated defintion for `T`. pub(crate) fn export_type_to_string() -> Result { let mut buffer = String::with_capacity(1024); @@ -160,7 +136,7 @@ pub(crate) fn export_type_to_string() -> Result() -> Result { path::absolute(Path::new( - &T::get_export_to() + T::EXPORT_TO .ok_or_else(|| std::any::type_name::()) .map_err(ExportError::CannotBeExported)?, )) @@ -182,7 +158,7 @@ fn generate_decl(out: &mut String) { /// Push an import statement for all dependencies of `T` fn generate_imports(out: &mut String) -> Result<(), ExportError> { let export_to = - T::get_export_to().ok_or(ExportError::CannotBeExported(std::any::type_name::()))?; + T::EXPORT_TO.ok_or(ExportError::CannotBeExported(std::any::type_name::()))?; let path = Path::new(&export_to); let deps = T::dependencies(); diff --git a/ts-rs/src/lib.rs b/ts-rs/src/lib.rs index 4f99ed9..bb88a13 100644 --- a/ts-rs/src/lib.rs +++ b/ts-rs/src/lib.rs @@ -165,9 +165,6 @@ use std::{ pub use ts_rs_macros::TS; pub use crate::export::ExportError; -// Used in generated code. Not public API -#[doc(hidden)] -pub use crate::export::__private; use crate::typelist::TypeList; #[cfg(feature = "chrono-impl")] @@ -304,10 +301,6 @@ pub trait TS { } } - fn get_export_to() -> Option { - Self::EXPORT_TO.map(ToString::to_string) - } - /// Declaration of this type, e.g. `interface User { user_id: number, ... }`. /// This function will panic if the type has no declaration. /// @@ -428,7 +421,7 @@ impl Dependency { /// If `T` is not exportable (meaning `T::EXPORT_TO` is `None`), this function will return /// `None` pub fn from_ty() -> Option { - let exported_to = T::get_export_to()?; + let exported_to = T::EXPORT_TO.map(ToOwned::to_owned)?; Some(Dependency { type_id: TypeId::of::(), ts_name: T::ident(), diff --git a/ts-rs/tests/docs.rs b/ts-rs/tests/docs.rs index d007ec4..1ede72d 100644 --- a/ts-rs/tests/docs.rs +++ b/ts-rs/tests/docs.rs @@ -4,6 +4,8 @@ use std::{concat, fs}; use ts_rs::TS; +const PATH: Option<&str> = std::option_env!("TS_RS_EXPORT_DIR"); + /* ============================================================================================== */ /// Doc comment. @@ -95,6 +97,16 @@ struct G { /* ============================================================================================== */ +fn generate_path(path: &str) -> String { + format!( + "{}{path}", + PATH + .map(|x| x.trim_end_matches('/')) + .map(|x| format!("{x}/")) + .unwrap_or_default() + ) +} + #[test] fn export_a() { A::export().unwrap(); @@ -136,7 +148,9 @@ fn export_a() { ) }; - let actual_content = fs::read_to_string("tests-out/docs/A.ts").unwrap(); + let actual_content = fs::read_to_string( + generate_path("tests-out/docs/A.ts") + ).unwrap(); assert_eq!(actual_content, expected_content); }