Skip to content

Commit

Permalink
Drop ExportConfig
Browse files Browse the repository at this point in the history
  • Loading branch information
oscartbeaumont committed Aug 1, 2024
1 parent 56362a5 commit 3087ba3
Show file tree
Hide file tree
Showing 4 changed files with 101 additions and 123 deletions.
16 changes: 5 additions & 11 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,32 +135,26 @@ impl<R: Runtime> Builder<R> {
.collect::<Result<Vec<_>, _>>()
.map(|v| v.join("\n"))?;

let cfg = crate::ExportConfig {
plugin_name: self.plugin_name.map(PluginName),
path: language.path.clone(),
header: language.header.clone(),
inner: language.clone(),
};

let rendered = crate::js_ts::render_all_parts::<specta_typescript::Typescript>(
&commands,
&self.events.1,
&self.types,
&Default::default(), // TODO: fix statics
&cfg,
&language,
&self.plugin_name,
&dependant_types,
crate::ts::GLOBALS,
)?;

write!(file, "{}", format!("{}\n{rendered}", cfg.inner.header))?;
write!(file, "{}", format!("{}\n{rendered}", language.header))?;

cfg.inner.run_format(path.clone()).ok();
language.run_format(path.clone()).ok();
}

Ok(())
}

pub fn export_js_doc(&self, language: Typescript) {
// TODO
todo!();
}
}
81 changes: 33 additions & 48 deletions src/js_ts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,29 @@ use specta::{
datatype::{DataType, FunctionResultVariant},
TypeMap,
};
use specta_typescript::ExportError;
use specta_typescript::{self as ts};
use specta_typescript::{ExportError, Typescript};

use crate::{EventDataType, ExportLanguage, ItemType, StaticCollection};
use crate::{apply_as_prefix, EventDataType, ItemType, LanguageExt, StaticCollection};

pub const DO_NOT_EDIT: &str = "// This file was generated by [tauri-specta](https://github.com/oscartbeaumont/tauri-specta). Do not edit this file manually.";
pub(crate) const DO_NOT_EDIT: &str = "// This file was generated by [tauri-specta](https://github.com/oscartbeaumont/tauri-specta). Do not edit this file manually.";
// TODO: Remove this
const CRINGE_ESLINT_DISABLE: &str = "/* eslint-disable */
";

pub type ExportConfig = crate::ExportConfig<specta_typescript::Typescript>;

pub fn render_all_parts<T: ExportLanguage<Config = specta_typescript::Typescript>>(
// TODO: Can we avoid hardcoding error type???
pub fn render_all_parts<T: LanguageExt<Error = ExportError>>(
commands: &[datatype::Function],
events: &[EventDataType],
type_map: &TypeMap,
statics: &StaticCollection,
// plugin_name: &str,
// cfg: &Typescript,
cfg: &ExportConfig,
cfg: &Typescript,
plugin_name: &Option<&'static str>,
dependant_types: &str,
globals: &str,
) -> Result<String, T::Error> {
let commands = T::render_commands(commands, type_map, cfg)?;
let events = T::render_events(events, type_map, cfg)?;
let commands = cfg.render_commands(commands, type_map, plugin_name)?;
let events = cfg.render_events(events, type_map, plugin_name)?;

let statics = statics
.statics
Expand Down Expand Up @@ -148,37 +147,31 @@ fn tauri_invoke(name: &str, arg_usages: Option<String>) -> String {
pub fn handle_result(
function: &datatype::Function,
type_map: &TypeMap,
cfg: &ExportConfig,
cfg: &Typescript,
) -> Result<String, ExportError> {
Ok(match &function.result() {
Some(FunctionResultVariant::Result(t, e)) => {
format!(
"Result<{}, {}>",
ts::datatype(
&cfg.inner,
&FunctionResultVariant::Value(t.clone()),
type_map
)?,
ts::datatype(
&cfg.inner,
&FunctionResultVariant::Value(e.clone()),
type_map
)?
ts::datatype(cfg, &FunctionResultVariant::Value(t.clone()), type_map)?,
ts::datatype(cfg, &FunctionResultVariant::Value(e.clone()), type_map)?
)
}
Some(FunctionResultVariant::Value(t)) => ts::datatype(
&cfg.inner,
&FunctionResultVariant::Value(t.clone()),
type_map,
)?,
Some(FunctionResultVariant::Value(t)) => {
ts::datatype(cfg, &FunctionResultVariant::Value(t.clone()), type_map)?
}
None => "void".to_string(),
})
}

pub fn command_body(cfg: &ExportConfig, function: &datatype::Function, as_any: bool) -> String {
let name = cfg
.plugin_name
.map(|n| n.apply_as_prefix(&function.name(), ItemType::Command))
pub fn command_body(
plugin_name: &Option<&'static str>,
function: &datatype::Function,
as_any: bool,
) -> String {
let name = plugin_name
.as_ref()
.map(|n| apply_as_prefix(&n, &function.name(), ItemType::Command))
.unwrap_or_else(|| function.name().to_string());

maybe_return_as_result_tuple(
Expand All @@ -194,13 +187,13 @@ pub fn command_body(cfg: &ExportConfig, function: &datatype::Function, as_any: b
)
}

pub fn events_map(events: &[EventDataType], cfg: &ExportConfig) -> String {
pub fn events_map(events: &[EventDataType], plugin_name: &Option<&'static str>) -> String {
events
.iter()
.map(|event| {
let name_str = cfg
.plugin_name
.map(|n| n.apply_as_prefix(event.name, ItemType::Event))
let name_str = plugin_name
.as_ref()
.map(|n| apply_as_prefix(n, event.name, ItemType::Event))
.unwrap_or_else(|| event.name.to_string());
let name_camel = event.name.to_lower_camel_case();

Expand All @@ -212,7 +205,7 @@ pub fn events_map(events: &[EventDataType], cfg: &ExportConfig) -> String {

pub fn events_types(
events: &[EventDataType],
cfg: &ExportConfig,
cfg: &Typescript,
type_map: &TypeMap,
) -> Result<Vec<String>, ExportError> {
events
Expand All @@ -221,7 +214,7 @@ pub fn events_types(
let name_camel = event.name.to_lower_camel_case();

let typ = ts::datatype(
&cfg.inner,
cfg,
&FunctionResultVariant::Value(event.typ.clone()),
type_map,
)?;
Expand All @@ -233,20 +226,12 @@ pub fn events_types(

pub fn events_data(
events: &[EventDataType],
cfg: &ExportConfig,
cfg: &Typescript,
plugin_name: &Option<&'static str>,
type_map: &TypeMap,
) -> Result<(Vec<String>, String), ExportError> {
Ok((
events_types(events, cfg, type_map)?,
events_map(events, cfg),
events_map(events, plugin_name),
))
}

impl From<specta_typescript::Typescript> for ExportConfig {
fn from(config: specta_typescript::Typescript) -> Self {
Self {
header: CRINGE_ESLINT_DISABLE.into(),
..Self::new(config)
}
}
}
84 changes: 46 additions & 38 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@

use std::{borrow::Cow, error, fmt, path::PathBuf};

use specta::{datatype, TypeMap};
use specta::{datatype, Language, TypeMap};

#[cfg(feature = "derive")]
#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
Expand All @@ -127,7 +127,7 @@ mod builder;
pub mod internal;
mod macros;

pub use builder::Builder; // TODO: Rename
pub use builder::Builder;

/// The exporter for [Javascript](https://www.javascript.com).
#[cfg(feature = "javascript")]
Expand All @@ -149,36 +149,32 @@ mod statics;
pub use event::*;
pub use statics::StaticCollection;

/// A set of functions that produce language-specific code
pub trait ExportLanguage: 'static {
type Config: Default + Clone; // TODO: Remove
type Error: fmt::Debug + error::Error + From<std::io::Error>; // TODO: Review if this `From<std::io::Error>` should be removed before stabilisation

fn run_format(path: PathBuf, cfg: &ExportConfig<Self::Config>);

fn render_events(
events: &[EventDataType],
pub trait LanguageExt: Language {
fn render_commands(
&self,
commands: &[datatype::Function],
type_map: &TypeMap,
cfg: &ExportConfig<Self::Config>,
plugin_name: &Option<&'static str>,
) -> Result<String, Self::Error>;

/// Renders a collection of [`FunctionDataType`] into a string.
fn render_commands(
commands: &[datatype::Function],
fn render_events(
&self,
events: &[EventDataType],
type_map: &TypeMap,
cfg: &ExportConfig<Self::Config>,
plugin_name: &Option<&'static str>,
) -> Result<String, Self::Error>;

/// Renders the output of [`globals`], [`render_functions`] and all dependant types into a TypeScript string.
fn render(
&self,
commands: &[datatype::Function],
events: &[EventDataType],
type_map: &TypeMap,
statics: &StaticCollection,
cfg: &ExportConfig<Self::Config>,
plugin_name: &Option<&'static str>,
) -> Result<String, Self::Error>;
}

// TODO: Remove
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct PluginName(&'static str);

Expand All @@ -205,25 +201,37 @@ impl PluginName {
}
}

/// The configuration for the generator
#[derive(Default, Clone)]
pub struct ExportConfig<TConfig> {
/// The name of the plugin to invoke.
///
/// If there is no plugin name (i.e. this is an app), this should be `None`.
pub(crate) plugin_name: Option<PluginName>,
/// The specta export configuration
pub(crate) inner: TConfig,
pub(crate) path: Option<PathBuf>,
pub(crate) header: Cow<'static, str>,
pub(crate) fn apply_as_prefix(plugin_name: &str, s: &str, item_type: ItemType) -> String {
format!(
"plugin:{}{}{}",
plugin_name,
match item_type {
ItemType::Event => ":",
ItemType::Command => "|",
},
s,
)
}

impl<TConfig: Default> ExportConfig<TConfig> {
/// Creates a new [`ExportConfiguration`] from a [`specta::ts::ExportConfiguration`]
pub fn new(config: TConfig) -> Self {
Self {
inner: config,
..Default::default()
}
}
}
// // TODO: Remove
// #[derive(Default, Clone)]
// pub struct ExportConfig<TConfig> {
// /// The name of the plugin to invoke.
// ///
// /// If there is no plugin name (i.e. this is an app), this should be `None`.
// pub(crate) plugin_name: Option<PluginName>,
// /// The specta export configuration
// pub(crate) inner: TConfig,
// pub(crate) path: Option<PathBuf>,
// pub(crate) header: Cow<'static, str>,
// }

// impl<TConfig: Default> ExportConfig<TConfig> {
// /// Creates a new [`ExportConfiguration`] from a [`specta::ts::ExportConfiguration`]
// pub fn new(config: TConfig) -> Self {
// Self {
// inner: config,
// ..Default::default()
// }
// }
// }
Loading

0 comments on commit 3087ba3

Please sign in to comment.