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

Namespacing same types #187

Merged
merged 17 commits into from
Jul 13, 2022
Merged
Show file tree
Hide file tree
Changes from 16 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
39 changes: 33 additions & 6 deletions tests/component_derive_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1111,6 +1111,24 @@ fn derive_struct_component_field_type_override() {
}
}

#[test]
fn derive_struct_component_field_type_path_override() {
let post = api_doc! {
struct Post {
id: i32,
#[component(value_type = path::to::Foo)]
value: i64,
}
};

let component_ref: &str = post
.pointer("/properties/value/$ref")
.unwrap()
.as_str()
.unwrap();
assert_eq!(component_ref, "#/components/schemas/path.to.Foo");
}

#[test]
fn derive_struct_component_field_type_override_with_format() {
let post = api_doc! {
Expand Down Expand Up @@ -1205,7 +1223,7 @@ fn derive_struct_override_type_with_a_reference() {

let value = api_doc! {
struct Value {
#[component(value_type = custom::NewBar)]
#[component(value_type = NewBar)]
field: String,
}
};
Expand Down Expand Up @@ -1364,11 +1382,20 @@ fn derive_component_with_generic_types_having_path_expression() {
}
};

assert_value! {ty=>
"properties.args.items.items.type" = r#""string""#, "Args items items type"
"properties.args.items.type" = r#""array""#, "Args items type"
"properties.args.type" = r#""array""#, "Args type"
}
let args = ty.pointer("/properties/args").unwrap();

assert_json_eq!(
args,
json!({
"items": {
"items": {
"type": "string"
},
"type": "array"
},
"type": "array"
})
);
}

#[test]
Expand Down
32 changes: 20 additions & 12 deletions tests/path_derive_rocket.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#![cfg(feature = "rocket_extras")]

use serde_json::Value;
use assert_json_diff::assert_json_eq;
use serde_json::{json, Value};
use utoipa::OpenApi;

mod common;
Expand Down Expand Up @@ -89,7 +90,7 @@ fn resolve_get_with_multiple_args() {
}

#[test]
fn resolve_get_with_optinal_query_args() {
fn resolve_get_with_optional_query_args() {
mod rocket_get_operation {
use rocket::get;

Expand Down Expand Up @@ -118,16 +119,23 @@ fn resolve_get_with_optinal_query_args() {
"expected paths.hello.get.parameters not null"
);

assert_value! {parameters=>
"[0].schema.type" = r#""array""#, "Query parameter type"
"[0].schema.format" = r#"null"#, "Query parameter format"
"[0].schema.items.type" = r#""string""#, "Query items parameter type"
"[0].schema.items.format" = r#"null"#, "Query items parameter format"
"[0].name" = r#""colors""#, "Query parameter name"
"[0].required" = r#"false"#, "Query parameter required"
"[0].deprecated" = r#"false"#, "Query parameter required"
"[0].in" = r#""query""#, "Query parameter in"
}
assert_json_eq!(
parameters,
json!([
{
"deprecated": false,
"in": "query",
"name": "colors",
"required": false,
"schema": {
"items": {
"type": "string",
},
"type": "array"
}
}
])
);
}

#[test]
Expand Down
29 changes: 28 additions & 1 deletion tests/request_body_derive_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ macro_rules! test_fn {
mod $name {
#[derive(utoipa::Component)]
/// Some struct
struct Foo {
pub struct Foo {
/// Some name
name: String,
}
Expand Down Expand Up @@ -94,6 +94,7 @@ fn derive_request_body_option_array_success() {
"paths.~1foo.post.requestBody.description" = r###"null"###, "Request body description"
}
}

test_fn! {
module: derive_request_body_primitive_simple,
body: = String
Expand Down Expand Up @@ -374,3 +375,29 @@ fn derive_request_body_complex_primitive_array_success() {
"paths.~1foo.post.requestBody.description" = r###""Create new foo references""###, "Request body description"
}
}

test_fn! {
module: derive_request_body_primitive_ref_path,
body: = path::to::Foo
}

#[test]
fn derive_request_body_primitive_ref_path_success() {
#[derive(OpenApi, Default)]
#[openapi(
handlers(derive_request_body_primitive_ref_path::post_foo),
components(derive_request_body_primitive_ref_path::Foo as path::to::Foo)
)]
struct ApiDoc;

let doc = serde_json::to_value(&ApiDoc::openapi()).unwrap();
let schemas = doc.pointer("/components/schemas").unwrap();
assert!(schemas.get("path.to.Foo").is_some());

let component_ref: &str = doc
.pointer("/paths/~1foo/post/requestBody/content/application~1json/schema/$ref")
.unwrap()
.as_str()
.unwrap();
assert_eq!(component_ref, "#/components/schemas/path.to.Foo");
}
2 changes: 1 addition & 1 deletion utoipa-gen/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,4 @@ chrono_with_format = []
json = []
decimal = []
rocket_extras = ["regex", "lazy_static"]
uuid = ["dep:uuid"]
uuid = ["dep:uuid"]
43 changes: 25 additions & 18 deletions utoipa-gen/src/component_type.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
use std::fmt::Display;

use proc_macro_error::abort_call_site;
use quote::{quote, ToTokens};

/// Tokenizes OpenAPI data type correctly according to the Rust type
pub struct ComponentType<'a, T: Display>(pub &'a T);
pub struct ComponentType<'a>(pub &'a syn::TypePath);

impl<'a, T> ComponentType<'a, T>
where
T: Display,
{
impl ComponentType<'_> {
/// Check whether type is known to be primitive in wich case returns true.
pub fn is_primitive(&self) -> bool {
let name = &*self.0.to_string();
let last_segment = match self.0.path.segments.last() {
Some(segment) => segment,
None => return false,
};
let name = &*last_segment.ident.to_string();

#[cfg(not(any(
feature = "chrono",
Expand Down Expand Up @@ -96,12 +96,12 @@ fn is_primitive_rust_decimal(name: &str) -> bool {
matches!(name, "Decimal")
}

impl<'a, T> ToTokens for ComponentType<'a, T>
where
T: Display,
{
impl ToTokens for ComponentType<'_> {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let name = &*self.0.to_string();
let last_segment = self.0.path.segments.last().unwrap_or_else(|| {
abort_call_site!("expected there to be at least one segment in the path")
});
let name = &*last_segment.ident.to_string();

match name {
"String" | "str" | "char" => {
Expand All @@ -127,12 +127,16 @@ where
}

/// Tokenizes OpenAPI data type format correctly by given Rust type.
pub struct ComponentFormat<T: Display>(pub(crate) T);
pub struct ComponentFormat<'a>(pub(crate) &'a syn::TypePath);

impl<T: Display> ComponentFormat<T> {
impl ComponentFormat<'_> {
/// Check is the format know format. Known formats can be used within `quote! {...}` statements.
pub fn is_known_format(&self) -> bool {
let name = &*self.0.to_string();
let last_segment = match self.0.path.segments.last() {
Some(segment) => segment,
None => return false,
};
let name = &*last_segment.ident.to_string();

#[cfg(not(any(feature = "chrono_with_format", feature = "uuid")))]
{
Expand Down Expand Up @@ -166,9 +170,12 @@ fn is_known_format(name: &str) -> bool {
)
}

impl<T: Display> ToTokens for ComponentFormat<T> {
impl ToTokens for ComponentFormat<'_> {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let name = &*self.0.to_string();
let last_segment = self.0.path.segments.last().unwrap_or_else(|| {
abort_call_site!("expected there to be at least one segment in the path")
});
let name = &*last_segment.ident.to_string();

match name {
"i8" | "i16" | "i32" | "u8" | "u16" | "u32" => {
Expand Down
4 changes: 2 additions & 2 deletions utoipa-gen/src/ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
use std::{borrow::Cow, cmp::Ordering};

use proc_macro2::{Ident, TokenStream};
use syn::{punctuated::Punctuated, token::Comma, Attribute, FnArg, ItemFn};
use syn::{punctuated::Punctuated, token::Comma, Attribute, FnArg, ItemFn, TypePath};

use crate::path::PathOperation;

Expand All @@ -21,7 +21,7 @@ pub enum Argument<'a> {
pub struct ArgumentValue<'a> {
pub name: Option<Cow<'a, str>>,
pub argument_in: ArgumentIn,
pub ident: Option<&'a Ident>,
pub type_path: Option<Cow<'a, TypePath>>,
pub is_array: bool,
pub is_option: bool,
}
Expand Down
6 changes: 3 additions & 3 deletions utoipa-gen/src/ext/actix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ impl ArgumentResolver for PathOperations {
resolved_path_args: Option<Vec<ResolvedArg>>,
) -> Option<Vec<Argument<'_>>> {
let (primitive_args, non_primitive_args): (Vec<Arg>, Vec<Arg>) = Self::get_fn_args(fn_args)
.partition(|arg| matches!(arg, Arg::Path(ty) if ComponentType(get_last_ident(ty).unwrap()).is_primitive()));
.partition(|arg| matches!(arg, Arg::Path(ty) if ComponentType(ty).is_primitive()));

if let Some(resolved_args) = resolved_path_args {
let primitive = Self::to_value_args(resolved_args, primitive_args);
Expand Down Expand Up @@ -89,8 +89,8 @@ impl PathOperations {
"ResolvedArg::Query is not reachable with primitive path type"
),
},
ident: match primitive_arg {
Arg::Path(arg_type) => get_last_ident(arg_type),
type_path: match primitive_arg {
Arg::Path(arg_type) => Some(Cow::Borrowed(arg_type)),
_ => {
unreachable!("Arg::Query is not reachable with primitive type")
}
Expand Down
38 changes: 22 additions & 16 deletions utoipa-gen/src/ext/rocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ impl ArgumentResolver for PathOperations {
Argument::Value(ArgumentValue {
name: Some(Cow::Owned(name)),
argument_in,
ident: Some(arg.ty),
type_path: Some(arg.ty),
is_array: arg.is_array,
is_option: arg.is_option,
})
Expand All @@ -61,7 +61,7 @@ impl ArgumentResolver for PathOperations {
Argument::Value(ArgumentValue {
name: Some(Cow::Owned(name)),
argument_in,
ident: None,
type_path: None,
is_array: false,
is_option: false,
})
Expand All @@ -74,7 +74,7 @@ impl ArgumentResolver for PathOperations {
#[cfg_attr(feature = "debug", derive(Debug))]
struct Arg<'a> {
name: &'a Ident,
ty: &'a Ident,
ty: Cow<'a, TypePath>,
is_array: bool,
is_option: bool,
}
Expand Down Expand Up @@ -115,28 +115,34 @@ impl PathOperations {
ordered_args.into_iter()
}

fn get_type_ident(ty: &Type) -> (&Ident, bool, bool) {
fn get_type_ident<'t>(ty: &'t Type) -> (Cow<'t, TypePath>, bool, bool) {
match ty {
Type::Path(path) => {
let segment = &path.path.segments.first().unwrap();
let first_segment: syn::PathSegment = path.path.segments.first().unwrap().clone();
let mut path: Cow<'t, TypePath> = Cow::Borrowed(path);

if segment.arguments.is_empty() {
(&segment.ident, false, false)
if first_segment.arguments.is_empty() {
return (path, false, false);
} else {
let is_array = segment.ident == "Vec";
let is_option = segment.ident == "Option";
let is_array = first_segment.ident == "Vec";
let is_option = first_segment.ident == "Option";

match segment.arguments {
match first_segment.arguments {
syn::PathArguments::AngleBracketed(ref angle_bracketed) => {
match angle_bracketed.args.first() {
Some(syn::GenericArgument::Type(arg)) => {
let child_type = Self::get_type_ident(arg);

(
child_type.0,
is_array || child_type.1,
is_option || child_type.2,
)
let is_array = is_array || child_type.1;
let is_option = is_option || child_type.2;

// Discard the current segment if we are one of the special
// types recognised as array or option
if is_array || is_option {
path = Cow::Owned(child_type.0.into_owned());
}

(path, is_array, is_option)
}
_ => abort_call_site!(
"unexpected generic type, expected GenericArgument::Type"
Expand Down Expand Up @@ -170,7 +176,7 @@ impl PathOperations {
let path = Self::get_type_path(pat_type.ty.as_ref());
let segment = &path.path.segments.first().unwrap();

let mut is_supported = ComponentType(&segment.ident).is_primitive();
let mut is_supported = ComponentType(path).is_primitive();

if !is_supported {
is_supported = matches!(&*segment.ident.to_string(), "Vec" | "Option")
Expand Down
Loading