From 543583841233f1b6e0ce18ec00ed91d013f0ce31 Mon Sep 17 00:00:00 2001 From: Moritz Bischof Date: Wed, 16 Dec 2020 01:22:28 +0100 Subject: [PATCH] add documentation & ci --- .github/workflows/test.yml | 14 ++++++ .gitignore | 2 +- README.md | 5 ++- macros/src/attr/enum.rs | 39 +++++++++-------- macros/src/lib.rs | 4 +- macros/src/utils.rs | 8 +++- ts-rs/src/lib.rs | 89 ++++++++++++++++++++++++++++++++++++++ 7 files changed, 135 insertions(+), 26 deletions(-) create mode 100644 .github/workflows/test.yml diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..502117a --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,14 @@ +on: [push] +name: Test +jobs: + test: + name: Test ts-rs + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + toolchain: stable + - uses: actions-rs/cargo@v1 + with: + command: test \ No newline at end of file diff --git a/.gitignore b/.gitignore index d410a35..8aef0ee 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ /target Cargo.lock /.idea -/example/bindings.ts \ No newline at end of file +bindings.ts \ No newline at end of file diff --git a/README.md b/README.md index dcef246..4ec0982 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ Generate TypeScript interface/type declarations from rust structs. [![Crate](https://img.shields.io/crates/v/ts-rs.svg)](https://crates.io/crates/ts-rs) [![API](https://docs.rs/ts-rs/badge.svg)](https://docs.rs/ts-rs) +[![Test](https://github.com/Aleph-Alpha/ts-rs/workflows/test/badge.svg)](https://github.com/Aleph-Alpha/ts-rs/actions) ## why? @@ -15,7 +16,7 @@ ts-rs might also come in handy when working with webassembly. ## how? -ts-rs exposes a single interface, `TS`. Using a derive macro, you can implement this interface for your types. +ts-rs exposes a single trait, `TS`. Using a derive macro, you can implement this interface for your types. Then, you can use this trait to obtain the TypeScript bindings. We recommend doing this in your tests. [see the example](https://github.com/Aleph-Alpha/ts-rs/blob/main/example/src/lib.rs) @@ -59,4 +60,4 @@ Please note that not all serde attributes are supported yet. - [x] serde compatibility layer - [ ] more customization - [ ] library support (chrono, uuids, ...) -- [ ] documentation \ No newline at end of file +- [x] documentation \ No newline at end of file diff --git a/macros/src/attr/enum.rs b/macros/src/attr/enum.rs index de56e81..91a5e74 100644 --- a/macros/src/attr/enum.rs +++ b/macros/src/attr/enum.rs @@ -1,7 +1,7 @@ use std::convert::TryFrom; +use crate::attr::{parse_assign_inflection, parse_assign_str, Inflection}; use syn::{Attribute, Ident, Result}; -use crate::attr::{Inflection, parse_assign_inflection, parse_assign_str}; #[derive(Default)] pub struct EnumAttr { @@ -25,24 +25,25 @@ impl EnumAttr { .for_each(|a| result.merge(a)); #[cfg(feature = "serde-compat")] - { - attrs - .iter() - .filter(|a| a.path.is_ident("serde")) - .flat_map(|attr| match SerdeEnumAttr::try_from(attr) { - Ok(attr) => Some(attr), - Err(_) => { - use quote::ToTokens; - crate::utils::print_warning( - "failed to parse serde attribute", - format!("{}", attr.to_token_stream()), - "ts-rs failed to parse this attribute. It will be ignored." - ).unwrap(); - None - } - }) - .for_each(|a| result.merge(a.0)); - } + { + attrs + .iter() + .filter(|a| a.path.is_ident("serde")) + .flat_map(|attr| match SerdeEnumAttr::try_from(attr) { + Ok(attr) => Some(attr), + Err(_) => { + use quote::ToTokens; + crate::utils::print_warning( + "failed to parse serde attribute", + format!("{}", attr.to_token_stream()), + "ts-rs failed to parse this attribute. It will be ignored.", + ) + .unwrap(); + None + } + }) + .for_each(|a| result.merge(a.0)); + } Ok(result) } diff --git a/macros/src/lib.rs b/macros/src/lib.rs index b5a455c..71eaedd 100644 --- a/macros/src/lib.rs +++ b/macros/src/lib.rs @@ -1,8 +1,6 @@ #![macro_use] #![deny(unused)] -//extern crate proc_macro; - use proc_macro2::{Ident, TokenStream}; use quote::quote; use syn::spanned::Spanned; @@ -37,6 +35,8 @@ impl DerivedTS { } } +/// Derives [TS](ts_rs::TS) for a struct or enum. +/// Please take a look at [TS](ts_rs::TS) for documentation. #[proc_macro_derive(TS, attributes(ts))] pub fn typescript(input: proc_macro::TokenStream) -> proc_macro::TokenStream { match entry(input) { diff --git a/macros/src/utils.rs b/macros/src/utils.rs index 59947ec..25935e9 100644 --- a/macros/src/utils.rs +++ b/macros/src/utils.rs @@ -46,7 +46,11 @@ macro_rules! impl_parse { } #[allow(unused)] -pub(crate) fn print_warning(title: impl Display, content: impl Display, note: impl Display) -> std::io::Result<()> { +pub(crate) fn print_warning( + title: impl Display, + content: impl Display, + note: impl Display, +) -> std::io::Result<()> { let make_color = |color: Color, bold: bool| { let mut spec = ColorSpec::new(); spec.set_fg(Some(color)).set_bold(bold).set_intense(true); @@ -83,4 +87,4 @@ pub(crate) fn print_warning(title: impl Display, content: impl Display, note: im writeln!(&mut buffer, "{}", note)?; writer.print(&buffer) -} \ No newline at end of file +} diff --git a/ts-rs/src/lib.rs b/ts-rs/src/lib.rs index 310b660..7ec0862 100644 --- a/ts-rs/src/lib.rs +++ b/ts-rs/src/lib.rs @@ -1,19 +1,108 @@ +//! Generate TypeScript interface/type declarations from rust structs. +//! +//! ## why? +//! When building a web application in rust, data structures have to be shared between backend and frontend. +//! Using this library, you can easily generate TypeScript bindings to your rust structs & enums, so that you can keep your +//! types in one place. +//! +//! ts-rs might also come in handy when working with webassembly. +//! +//! ## how? +//! ts-rs exposes a single trait, `TS`. +//! Using a derive macro, you can implement this interface for +//! your types. +//! Then, you can use this trait to obtain the TypeScript bindings. +//! We recommend doing this in your tests. [see the example](https://github.com/Aleph-Alpha/ts-rs/blob/main/example/src/lib.rs) +//! +//! ## serde compatibility layer +//! With the `serde-compat` feature enabled, ts-rs tries parsing serde attributes. +//! Please note that not all serde attributes are supported yet. + use std::fs::OpenOptions; use std::io::{BufWriter, Write}; use std::path::Path; pub use ts_rs_macros::TS; +/// A type which can be represented in TypeScript. +/// Most of the time, you'd want to derive this trait instead of implementing it manually. +/// ts-rs comes with implementations for all numeric types, `String`, `Vec`, `Option` and tuples. +/// +/// ## get started +/// [TS](ts_rs::TS) can easily be derived for structs and enums: +/// ```rust +/// use ts_rs::TS; +/// +/// #[derive(TS)] +/// struct User { +/// first_name: String, +/// last_name: String, +/// } +/// ``` +/// To actually obtain the bindings, you can call `User::dump` to write the bindings to a file: +/// ```rust +/// # use ts_rs::TS; +/// +/// # #[derive(TS)] +/// # struct User { +/// # first_name: String, +/// # last_name: String, +/// # } +/// std::fs::remove_file("bindings.ts").ok(); +/// User::dump("bindings.ts").unwrap(); +/// ``` +/// +/// ### struct attributes +/// +/// - `#[ts(rename = "..")]`: +/// Set the name of the generated interface +/// +/// - `#[ts(rename_all = "..")]`: +/// Rename all fields of this struct. +/// Valid values are `lowercase`, `UPPERCASE`, `camelCase`, `snake_case`, `PascalCase`, `SCREAMING_SNAKE_CASE` +/// +/// ### struct field attributes +/// +/// - `#[ts(type = "..")]`: +/// Overrides the type used in TypeScript +/// +/// - `#[ts(rename = "..")]`: +/// Renames this field +/// +/// - `#[ts(inline)]`: +/// Inlines the type of this field +/// +/// ### enum attributes +/// +/// - `#[ts(rename = "..")]`: +/// Set the name of the generated type +/// +/// - `#[ts(rename_all = "..")]`: +/// Rename all variants of this enum. +/// Valid values are `lowercase`, `UPPERCASE`, `camelCase`, `snake_case`, `PascalCase`, `SCREAMING_SNAKE_CASE` +/// +/// ### enum variant attributes +/// +/// - `#[ts(rename = "..")]`: +/// Renames this variant +/// + pub trait TS { /// Declaration of this type, e.g. `interface User { user_id: number, ... }`, if available. fn decl() -> Option { None } + /// Formats this type. /// When using inline, this will return the definition of the type. /// Otherwise, it's name is returned (if the type is named) fn format(indent: usize, inline: bool) -> String; + /// Dumps the declaration of this type to a file. + /// If the file does not exist, it will be created. + /// If it does, the declaration will be appended. + /// + /// This function will panicked when called on a type which does not have a declaration. fn dump(out: impl AsRef) -> std::io::Result<()> { let out = out.as_ref(); let file = OpenOptions::new()