add documentation & ci

This commit is contained in:
Moritz Bischof
2020-12-16 01:22:28 +01:00
parent 4e9b3ad708
commit 5435838412
7 changed files with 135 additions and 26 deletions
+14
View File
@@ -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
+1 -1
View File
@@ -1,4 +1,4 @@
/target
Cargo.lock
/.idea
/example/bindings.ts
bindings.ts
+3 -2
View File
@@ -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
- [x] documentation
+20 -19
View File
@@ -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)
}
+2 -2
View File
@@ -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) {
+6 -2
View File
@@ -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)
}
}
+89
View File
@@ -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<String> {
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<Path>) -> std::io::Result<()> {
let out = out.as_ref();
let file = OpenOptions::new()