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

proof-of-concept of type overrides using the CLI #334

Draft
wants to merge 7 commits into
base: cli
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
54 changes: 54 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
clap = { version = "4", features = ["derive"]}
clap = { version = "4", features = ["derive"] }
color-eyre = "0.6"
serde = { version = "1", features = ["derive"] }
toml = "0.8"
48 changes: 0 additions & 48 deletions cli/src/args.rs

This file was deleted.

18 changes: 12 additions & 6 deletions cli/src/cargo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ use std::process::{Command, Stdio};

use color_eyre::Result;

use crate::{args::Args, path};
use crate::config::Config;
use crate::path;

macro_rules! feature {
($cargo_invocation: expr, $args: expr, { $($field: ident => $feature: literal),* $(,)? }) => {
Expand All @@ -16,7 +17,7 @@ macro_rules! feature {
};
}

pub fn invoke(args: &Args) -> Result<()> {
pub fn invoke(cfg: &Config) -> Result<()> {
let mut cargo_invocation = Command::new("cargo");

cargo_invocation
Expand All @@ -26,20 +27,25 @@ pub fn invoke(args: &Args) -> Result<()> {
.arg("ts-rs/export")
.arg("--features")
.arg("ts-rs/generate-metadata")
.stdout(if args.no_capture {
.stdout(if cfg.no_capture {
Stdio::inherit()
} else {
Stdio::piped()
})
.env("TS_RS_EXPORT_DIR", path::absolute(&args.output_directory)?);
.env("TS_RS_EXPORT_DIR", path::absolute(&cfg.output_directory)?);

feature!(cargo_invocation, args, {
for (rust, ts) in &cfg.overrides {
let env = format!("TS_RS_INTERNAL_OVERRIDE_{rust}");
cargo_invocation.env(env, ts);
}
Comment on lines +36 to +39
Copy link
Collaborator Author

@NyxCode NyxCode Jun 21, 2024

Choose a reason for hiding this comment

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

  1. The CLI reads the config file, and sets an environment variable for each override


feature!(cargo_invocation, cfg, {
no_warnings => "no-serde-warnings",
esm_imports => "import-esm",
format => "format",
});

if args.no_capture {
if cfg.no_capture {
cargo_invocation.arg("--").arg("--nocapture");
} else {
cargo_invocation.arg("--quiet");
Expand Down
104 changes: 104 additions & 0 deletions cli/src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
use clap::Parser;
use color_eyre::Result;
use serde::Deserialize;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use color_eyre::eyre::bail;

#[derive(Parser, Debug)]
#[allow(clippy::struct_excessive_bools)]
pub struct Args {
/// Defines where your TS bindings will be saved by setting TS_RS_EXPORT_DIR
#[arg(long, short)]
pub output_directory: PathBuf,

/// Disables warnings caused by using serde attributes that ts-rs cannot process
#[arg(long)]
pub no_warnings: bool,

/// Adds the ".js" extension to import paths
#[arg(long)]
pub esm_imports: bool,

/// Formats the generated TypeScript files
#[arg(long)]
pub format: bool,

/// Generates an index.ts file in your --output-directory that re-exports all
/// types generated by ts-rs
#[arg(long = "index")]
pub generate_index_ts: bool,

/// Generates only a single index.ts file in your --output-directory that
/// contains all exported types
#[arg(long = "merge")]
pub merge_files: bool,

/// Do not capture `cargo test`'s output, and pass --nocapture to the test binary
#[arg(long = "nocapture")]
pub no_capture: bool,
}

// keeping this separate from `Args` for now :shrug:
#[derive(Default, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct Config {
// type overrides for types implemented inside ts-rs.
pub overrides: HashMap<String, String>,
pub output_directory: PathBuf,
pub no_warnings: bool,
pub esm_imports: bool,
pub format: bool,
pub generate_index_ts: bool,
pub merge_files: bool,
pub no_capture: bool,
}

impl Config {
pub fn load() -> Result<Self> {
let mut cfg = Self::load_from_file()?;
cfg.merge(Args::parse());
cfg.verify()?;
Ok(cfg)
}

fn load_from_file() -> Result<Self> {
// TODO: from where do we actually load the config?
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think there should be a CLI flag like --config <PATH> and ./ts-rs.toml or maybe ./ts-rs/config.toml should be a default location if the flag isn't provided

let path = Path::new("./ts-rs.toml");
if !path.is_file() {
return Ok(Self::default());
}
let content = std::fs::read_to_string(path)?;
Ok(toml::from_str::<Config>(&content)?)
}

fn verify(&self) -> Result<()> {
if self.merge_files && self.generate_index_ts {
bail!("--index is not compatible with --merge");
}
Ok(())
}

fn merge(
&mut self,
Args {
output_directory,
no_warnings,
esm_imports,
format,
generate_index_ts,
merge_files,
no_capture,
}: Args,
) {
self.output_directory = output_directory;
self.no_warnings = no_warnings;
self.esm_imports = esm_imports;
self.format = format;
self.generate_index_ts = generate_index_ts;
self.merge_files = merge_files;
self.no_capture = no_capture;
}
}


38 changes: 19 additions & 19 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,45 +5,45 @@ use std::{
io::{Read, Write},
};

use clap::Parser;
use color_eyre::{owo_colors::OwoColorize, Result};

mod args;
mod cargo;
mod metadata;
mod path;
mod config;

use args::Args;
use metadata::{Metadata, FILE_NAME};
use crate::config::Config;

const BLANK_LINE: [u8; 2] = [b'\n', b'\n'];
const NOTE: &[u8; 109] = b"// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.\n";

struct Cleanup<'a>(&'a Config);
impl<'a> Drop for Cleanup<'a> {
fn drop(&mut self) {
_ = fs::remove_file(self.0.output_directory.join(FILE_NAME));
}
}

gustavo-shigueo marked this conversation as resolved.
Show resolved Hide resolved
fn main() -> Result<()> {
color_eyre::install()?;

let args = Args::parse();
let cfg = Config::load()?;
let _cleanup = Cleanup(&cfg);

let metadata_path = args.output_directory.join(FILE_NAME);
let metadata_path = cfg.output_directory.join(FILE_NAME);
if metadata_path.exists() {
fs::remove_file(&metadata_path)?;
}

if args.merge_files && args.generate_index_ts {
eprintln!(
"{} --index is not compatible with --merge",
"Error:".red().bold()
);

return Ok(());
}

cargo::invoke(&args)?;
cargo::invoke(&cfg)?;

let metadata_content = fs::read_to_string(&metadata_path)?;
let metadata = Metadata::try_from(&*metadata_content)?;

let demand_unique_names = args.merge_files || args.generate_index_ts;
let demand_unique_names = cfg.merge_files || cfg.generate_index_ts;

if !demand_unique_names || metadata.is_empty() {
return Ok(());
Expand All @@ -60,7 +60,7 @@ fn main() -> Result<()> {
return Ok(());
}

let index_path = args.output_directory.join("index.ts");
let index_path = cfg.output_directory.join("index.ts");

if index_path.exists() {
fs::remove_file(&index_path)?;
Expand All @@ -73,17 +73,17 @@ fn main() -> Result<()> {

index.write_all(NOTE)?;

if args.generate_index_ts {
if cfg.generate_index_ts {
for path in metadata.export_paths() {
index.write_fmt(format_args!("\nexport * from {path:?};"))?;
}

return Ok(());
}

if args.merge_files {
if cfg.merge_files {
for path in metadata.export_paths() {
let path = path::absolute(args.output_directory.join(path))?;
let path = path::absolute(cfg.output_directory.join(path))?;
let mut file = OpenOptions::new().read(true).open(&path)?;

let mut buf = Vec::with_capacity(file.metadata()?.len().try_into()?);
Expand All @@ -98,7 +98,7 @@ fn main() -> Result<()> {
fs::remove_file(path)?;
}

path::remove_empty_subdirectories(&args.output_directory)?;
path::remove_empty_subdirectories(&cfg.output_directory)?;

return Ok(());
}
Expand Down
Loading