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 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
45 changes: 45 additions & 0 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,6 @@ Feel free to open an issue, discuss using GitHub discussions or open a PR.
[See CONTRIBUTING.md](https://github.com/Aleph-Alpha/ts-rs/blob/main/CONTRIBUTING.md)

### MSRV
The Minimum Supported Rust Version for this crate is 1.63.0
The Minimum Supported Rust Version for this crate is 1.72.0

License: MIT
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.

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

use color_eyre::Result;

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

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

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

cargo_invocation
Expand All @@ -26,20 +26,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
153 changes: 153 additions & 0 deletions cli/src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
use std::{
collections::HashMap,
path::{Path, PathBuf},
};

use clap::Parser;
use color_eyre::{eyre::bail, owo_colors::OwoColorize, Result};
use serde::Deserialize;

#[derive(Parser, Debug)]
#[allow(clippy::struct_excessive_bools)]
pub struct Args {
#[clap(skip)]
pub overrides: HashMap<String, String>,

/// Path to the `ts-rs` config file
#[arg(long)]
pub config: Option<PathBuf>,

/// Defines where your TS bindings will be saved by setting `TS_RS_EXPORT_DIR`
#[arg(long, short)]
pub output_directory: Option<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, rename_all = "kebab-case")]
#[allow(clippy::struct_excessive_bools)]
pub struct Config {
/// Type overrides for types implemented inside ts-rs.
pub overrides: HashMap<String, String>,
pub output_directory: Option<PathBuf>,
pub no_warnings: bool,
pub esm_imports: bool,
pub format: bool,

#[serde(rename = "index")]
pub generate_index_ts: bool,

#[serde(rename = "merge")]
pub merge_files: bool,

#[serde(rename = "nocapture")]
pub no_capture: bool,
}

impl Args {
pub fn load() -> Result<Self> {
let mut args = Self::parse();

let cfg = Config::load_from_file(args.config.as_deref())?;

args.merge(cfg);
args.verify()?;

Ok(args)
}

pub fn output_directory(&self) -> &Path {
self.output_directory
.as_deref()
.expect("Output directory must not be `None`")
}

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

if self.output_directory.is_none() {
bail!("{}: You must provide the output diretory, either through the config file or the --output-directory flag", "Error".bold().red())
}

Ok(())
}

fn merge(
&mut self,
Config {
overrides,
output_directory,
no_warnings,
esm_imports,
format,
generate_index_ts,
merge_files,
no_capture,
}: Config,
) {
// QUESTION: This gives the CLI flag priority over the config file's value,
// is this the correct order?
self.output_directory = output_directory.or_else(|| self.output_directory.clone());

self.overrides = overrides;
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;
}
}

impl Config {
fn load_from_file(path: Option<&Path>) -> Result<Self> {
if let Some(path) = path {
if !path.is_file() {
bail!("The provided path doesn't exist");
}

let content = std::fs::read_to_string(path)?;
return Ok(toml::from_str(&content)?);
}

// TODO: from where do we actually load the config?
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(&content)?)
}
}
Loading