From 4e903909ba8e1dfadcb715504f2157cd76a6b134 Mon Sep 17 00:00:00 2001 From: xazukx <> Date: Mon, 15 Sep 2025 17:51:48 -0600 Subject: [PATCH] Add env for generating an index file. Rename other env. --- macros/src/lib.rs | 2 +- ts-rs/src/export.rs | 94 +++++++++++++++++++++++++++++++++++++++++++-- ts-rs/src/lib.rs | 12 ++++-- 3 files changed, 101 insertions(+), 7 deletions(-) diff --git a/macros/src/lib.rs b/macros/src/lib.rs index 6d28a13..fac00ec 100644 --- a/macros/src/lib.rs +++ b/macros/src/lib.rs @@ -62,7 +62,7 @@ impl DerivedTS { // Optionally prefix with the current crate name to avoid cross-crate overwrites // when multiple crates export to the same output directory during tests. - let prefix_crate = std::env::var("PREFIX_CRATE_NAME_AS_FOLDER") + let prefix_crate = std::env::var("TS_RS_CRATE_NAME_AS_FOLDER") .map(|v| { let v = v.to_ascii_lowercase(); matches!(v.as_str(), "1" | "true" | "yes" | "on") diff --git a/ts-rs/src/export.rs b/ts-rs/src/export.rs index 5fc01b3..ab22c5d 100644 --- a/ts-rs/src/export.rs +++ b/ts-rs/src/export.rs @@ -1,7 +1,6 @@ use std::{ any::TypeId, borrow::Cow, collections::{BTreeMap, BTreeSet, HashMap, HashSet}, fmt::Write, fs::File, io::{Seek, SeekFrom}, path::{Component, Path, PathBuf}, sync::{Mutex, OnceLock} }; - pub use error::ExportError; use path::diff_paths; pub(crate) use recursive_export::export_all_into; @@ -11,13 +10,99 @@ use crate::TS; mod error; mod path; +const NOTE: &str = "// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.\n"; + +fn truthy_env(var: &str) -> bool { + std::env::var(var) + .map(|v| { + let v = v.to_ascii_lowercase(); + matches!(v.as_str(), "1" | "true" | "yes" | "on") + }) + .unwrap_or(false) +} + +fn maybe_update_index(path: &Path) -> Result<(), ExportError> { + if !truthy_env("TS_RS_GENERATE_INDEX") { + return Ok(()); + } + + let Some(parent) = path.parent() else { return Ok(()); }; + let Some(stem) = path.file_stem().and_then(std::ffi::OsStr::to_str) else { return Ok(()); }; + let index_path = parent.join("index.ts"); + + // Compute the module path to re-export from this index file + let mut module_path = format!("./{}", stem); + if cfg!(feature = "import-esm") { + module_path.push_str(".js"); + } + + let lock = &mut get_index_paths().lock().unwrap(); + + // Initialize set with existing entries if we see this index file for the first time in this process + let set = lock.entry(index_path.clone()).or_insert_with(|| { + let mut existing = HashSet::new(); + if let Ok(mut f) = std::fs::OpenOptions::new().read(true).open(&index_path) { + use std::io::Read; + let mut s = String::new(); + if f.read_to_string(&mut s).is_ok() { + for line in s.lines() { + let line = line.trim(); + if let Some(start) = line.find("export * from ") { + let rest = &line[start + "export * from ".len()..]; + if let Some(first_quote) = rest.find('"') { + let rest = &rest[first_quote + 1..]; + if let Some(end_quote) = rest.find('"') { + let path_part = &rest[..end_quote]; + existing.insert(path_part.to_string()); + } + } + } + } + } + } + existing + }); + + if set.contains(&module_path) { + return Ok(()); + } + + // Ensure the index file exists and has a header when created + if !index_path.exists() { + use std::io::Write as _; + let mut f = File::create(&index_path)?; + f.write_all(NOTE.as_bytes())?; + f.write_all(b"\n")?; + f.sync_all()?; + } + + // Append the new export line + { + use std::io::Write as _; + let mut f = std::fs::OpenOptions::new() + .write(true) + .append(true) + .open(&index_path)?; + writeln!(f, "export * from \"{}\";", module_path)?; + f.sync_all()?; + } + + set.insert(module_path); + + Ok(()) +} + + static EXPORT_PATHS: OnceLock>>> = OnceLock::new(); +static INDEX_PATHS: OnceLock>>> = OnceLock::new(); fn get_export_paths<'a>() -> &'a Mutex>> { EXPORT_PATHS.get_or_init(Default::default) } -const NOTE: &str = "// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.\n"; +fn get_index_paths<'a>() -> &'a Mutex>> { + INDEX_PATHS.get_or_init(Default::default) +} mod recursive_export { use std::{any::TypeId, collections::HashSet, path::Path}; @@ -119,7 +204,10 @@ pub(crate) fn export_to>( std::fs::create_dir_all(parent)?; } - export_and_merge(path, type_name, buffer)?; + export_and_merge(path.clone(), type_name, buffer)?; + + // Optionally update index.ts in the directory of the written file + maybe_update_index(&path)?; Ok(()) } diff --git a/ts-rs/src/lib.rs b/ts-rs/src/lib.rs index aa9ff5b..b3ce02e 100644 --- a/ts-rs/src/lib.rs +++ b/ts-rs/src/lib.rs @@ -169,13 +169,19 @@ mod tokio; /// dependencies will be written to `TS_RS_EXPORT_DIR`, or `./bindings` by default. /// /// If you have multiple crates exporting to the same directory (for example in a Cargo workspace), -/// you can set the environment variable `PREFIX_CRATE_NAME_AS_FOLDER` to a truthy value (`1`, +/// you can set the environment variable `TS_RS_CRATE_NAME_AS_FOLDER` to a truthy value (`1`, /// `true`, `yes`, or `on`). When enabled, the current crate name (from `CARGO_PKG_NAME`) will be /// inserted as a folder inside the export directory before the generated file path. This avoids /// cross-crate overwrites by writing to `TS_RS_EXPORT_DIR//`. -/// Example: with `PREFIX_CRATE_NAME_AS_FOLDER=1` and `#[ts(export)] struct User;`, the output will +/// Example: with `TS_RS_CRATE_NAME_AS_FOLDER=1` and `#[ts(export)] struct User;`, the output will /// be `./bindings//User.ts` by default. /// +/// You can optionally generate an `index.ts` file in each output directory that re-exports every +/// generated file there with `export * from "./";` lines by setting +/// `TS_RS_GENERATE_INDEX` to a truthy value (`1`, `true`, `yes`, or `on`). When the +/// `import-esm` feature is enabled, the re-export paths will use the `.js` extension to comply with +/// ESM semantics. The index file is updated incrementally and avoids duplicate entries across runs. +/// /// For each individual type, path and filename within the output directory can be changed using /// `#[ts(export_to = "...")]`. By default, the filename will be derived from the name of the type. /// @@ -213,7 +219,7 @@ mod tokio; /// ``` ///
/// To avoid overwriting files when exporting from multiple crates into the same directory, you -/// may also set `PREFIX_CRATE_NAME_AS_FOLDER` to a truthy value (`1`, `true`, `yes`, or `on`). +/// may also set `TS_RS_CRATE_NAME_AS_FOLDER` to a truthy value (`1`, `true`, `yes`, or `on`). /// When enabled, the generated file paths are prefixed with the current crate name (from /// `CARGO_PKG_NAME`). ///