Add env for generating an index file. Rename other env.

This commit is contained in:
xazukx
2025-09-15 17:51:48 -06:00
parent cea1387999
commit 4e903909ba
3 changed files with 101 additions and 7 deletions
+1 -1
View File
@@ -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")
+91 -3
View File
@@ -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<Mutex<HashMap<PathBuf, HashSet<String>>>> = OnceLock::new();
static INDEX_PATHS: OnceLock<Mutex<HashMap<PathBuf, HashSet<String>>>> = OnceLock::new();
fn get_export_paths<'a>() -> &'a Mutex<HashMap<PathBuf, HashSet<String>>> {
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<HashMap<PathBuf, HashSet<String>>> {
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<T: TS + ?Sized + 'static, P: AsRef<Path>>(
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(())
}
+9 -3
View File
@@ -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/<crate-name>/<path>`.
/// 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/<crate-name>/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 "./<file>";` 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;
/// ```
/// <br/>
/// 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`).
///