diff --git a/utoipa-config/src/lib.rs b/utoipa-config/src/lib.rs index f282d91f..19617f73 100644 --- a/utoipa-config/src/lib.rs +++ b/utoipa-config/src/lib.rs @@ -191,10 +191,7 @@ impl<'c> Config<'c> { } fn get_out_dir() -> Option { - match std::env::var("OUT_DIR") { - Ok(out_dir) => Some(out_dir), - Err(_) => None, - } + std::env::var("OUT_DIR").ok() } /// Write the current [`Config`] to a file. This persists the [`Config`] for `utoipa` to read diff --git a/utoipa-gen/src/component.rs b/utoipa-gen/src/component.rs index 90bce51d..a767c886 100644 --- a/utoipa-gen/src/component.rs +++ b/utoipa-gen/src/component.rs @@ -137,7 +137,7 @@ pub trait SynPathExt { fn rewrite_path(&self) -> Result; } -impl<'p> SynPathExt for &'p Path { +impl SynPathExt for &Path { fn rewrite_path(&self) -> Result { let last_segment = self .segments diff --git a/utoipa-gen/src/component/features/attributes.rs b/utoipa-gen/src/component/features/attributes.rs index cb343b2f..ca676f20 100644 --- a/utoipa-gen/src/component/features/attributes.rs +++ b/utoipa-gen/src/component/features/attributes.rs @@ -497,7 +497,7 @@ impl_feature! { impl ValueType { /// Create [`TypeTree`] from current [`syn::Type`]. - pub fn as_type_tree(&self) -> Result { + pub fn as_type_tree(&self) -> Result, Diagnostics> { TypeTree::from_type(&self.0) } } diff --git a/utoipa-gen/src/component/features/validators.rs b/utoipa-gen/src/component/features/validators.rs index f0ba2fe1..355d7e1f 100644 --- a/utoipa-gen/src/component/features/validators.rs +++ b/utoipa-gen/src/component/features/validators.rs @@ -31,6 +31,7 @@ impl Validator for IsString<'_> { } } +#[allow(dead_code)] pub struct IsInteger<'a>(&'a SchemaType<'a>); impl Validator for IsInteger<'_> { diff --git a/utoipa-gen/src/component/schema.rs b/utoipa-gen/src/component/schema.rs index 9f09bc2b..0067df4a 100644 --- a/utoipa-gen/src/component/schema.rs +++ b/utoipa-gen/src/component/schema.rs @@ -188,7 +188,7 @@ impl ToTokensDiagnostics for Schema<'_> { enum SchemaVariant<'a> { Named(NamedStructSchema), Unnamed(UnnamedStructSchema), - Enum(EnumSchema<'a>), + Enum(Box>), Unit(UnitStructVariant), } @@ -226,7 +226,10 @@ impl<'a> SchemaVariant<'a> { } Fields::Unit => Ok(Self::Unit(UnitStructVariant::new(root)?)), }, - Data::Enum(content) => Ok(Self::Enum(EnumSchema::new(root, &content.variants)?)), + Data::Enum(content) => Ok(Self::Enum(Box::new(EnumSchema::new( + root, + &content.variants, + )?))), _ => Err(Diagnostics::with_span( root.ident.span(), "unexpected data type, expected syn::Data::Struct or syn::Data::Enum", diff --git a/utoipa-gen/src/ext.rs b/utoipa-gen/src/ext.rs index 4d1eda1c..cf2290f1 100644 --- a/utoipa-gen/src/ext.rs +++ b/utoipa-gen/src/ext.rs @@ -288,7 +288,7 @@ pub trait ArgumentResolver { _: &'_ Punctuated, _: Option>, _: String, - ) -> Result { + ) -> Result, Diagnostics> { Ok((None, None, None)) } } @@ -400,7 +400,7 @@ pub mod fn_arg { pub fn get_fn_args( fn_args: &Punctuated, - ) -> Result, Diagnostics> { + ) -> Result>, Diagnostics> { fn_args .iter() .filter_map(|arg| { diff --git a/utoipa-gen/src/ext/actix.rs b/utoipa-gen/src/ext/actix.rs index ee741d72..8f9c600a 100644 --- a/utoipa-gen/src/ext/actix.rs +++ b/utoipa-gen/src/ext/actix.rs @@ -22,7 +22,7 @@ impl ArgumentResolver for PathOperations { fn_args: &Punctuated, macro_args: Option>, _: String, - ) -> Result { + ) -> Result, Diagnostics> { let (into_params_args, value_args): (Vec, Vec) = fn_arg::get_fn_args(fn_args)?.partition(fn_arg::is_into_params); diff --git a/utoipa-gen/src/lib.rs b/utoipa-gen/src/lib.rs index d1c799d0..c730bc87 100644 --- a/utoipa-gen/src/lib.rs +++ b/utoipa-gen/src/lib.rs @@ -152,7 +152,7 @@ static CONFIG: once_cell::sync::Lazy = /// * `write_only` Defines property is only used in **write** operations *POST,PUT,PATCH* but not in *GET* /// * `read_only` Defines property is only used in **read** operations *GET* but not in *POST,PUT,PATCH* /// * `xml(...)` Can be used to define [`Xml`][xml] object properties applicable to named fields. -/// See configuration options at xml attributes of [`ToSchema`][to_schema_xml] +/// See configuration options at xml attributes of [`ToSchema`][to_schema_xml] /// * `value_type = ...` Can be used to override default type derived from type of the field used in OpenAPI spec. /// This is useful in cases where the default type does not correspond to the actual type e.g. when /// any third-party types are used which are not [`ToSchema`][to_schema]s nor [`primitive` types][primitive]. @@ -200,7 +200,7 @@ static CONFIG: once_cell::sync::Lazy = /// * `content_media_type = ...` Can be used to define MIME type of a string for underlying schema object. /// See [`Object::content_media_type`][schema_object_media_type] ///* `ignore` or `ignore = ...` Can be used to skip the field from being serialized to OpenAPI schema. It accepts either a literal `bool` value -/// or a path to a function that returns `bool` (`Fn() -> bool`). +/// or a path to a function that returns `bool` (`Fn() -> bool`). ///* `no_recursion` Is used to break from recursion in case of looping schema tree e.g. `Pet` -> /// `Owner` -> `Pet`. _`no_recursion`_ attribute must be used within `Owner` type not to allow /// recurring into `Pet`. Failing to do so will cause infinite loop and runtime **panic**. @@ -487,7 +487,7 @@ static CONFIG: once_cell::sync::Lazy = /// This attribute requires that a `tag` is present, otherwise serde will trigger a compile-time /// failure. /// * `untagged` Supported at the container level. Allows [untagged -/// enum representation](https://serde.rs/enum-representations.html#untagged). +/// enum representation](https://serde.rs/enum-representations.html#untagged). /// * `default` Supported at the container level and field level according to [serde attributes]. /// * `deny_unknown_fields` Supported at the container level. /// * `flatten` Supported at the field level. @@ -1160,7 +1160,7 @@ pub fn derive_to_schema(input: TokenStream) -> TokenStream { /// _`serde_json::json!`_ can parse as a _`serde_json::Value`_. /// /// * `response = ...` Type what implements [`ToResponse`][to_response_trait] trait. This can alternatively be used to -/// define response attributes. _`response`_ attribute cannot co-exist with other than _`status`_ attribute. +// define response attributes. _`response`_ attribute cannot co-exist with other than _`status`_ attribute. /// /// * `content((...), (...))` Can be used to define multiple return types for single response status. Supports same syntax as /// [multiple request body content][`macro@path#multiple-request-body-content`]. @@ -1339,7 +1339,7 @@ pub fn derive_to_schema(input: TokenStream) -> TokenStream { /// E.g. _`Path, Query, Header, Cookie`_ /// /// * `deprecated` Define whether the parameter is deprecated or not. Can optionally be defined -/// with explicit `bool` value as _`deprecated = bool`_. +// with explicit `bool` value as _`deprecated = bool`_. /// /// * `description = "..."` Define possible description for the parameter as str. /// @@ -1369,7 +1369,7 @@ pub fn derive_to_schema(input: TokenStream) -> TokenStream { /// * `read_only` Defines property is only used in **read** operations *GET* but not in *POST,PUT,PATCH* /// /// * `xml(...)` Can be used to define [`Xml`][xml] object properties for the parameter type. -/// See configuration options at xml attributes of [`ToSchema`][to_schema_xml] +// See configuration options at xml attributes of [`ToSchema`][to_schema_xml] /// /// * `nullable` Defines property is nullable (note this is different to non-required). /// @@ -1558,7 +1558,7 @@ pub fn derive_to_schema(input: TokenStream) -> TokenStream { /// 1. It allows users to use tuple style path parameters e.g. _`Path((id, name)): Path<(i32, String)>`_ and resolves /// parameter names and types from it. /// 2. It enhances [`IntoParams` derive][into_params_derive] functionality by automatically resolving _`parameter_in`_ from -/// _`Path<...>`_ or _`Query<...>`_ handler function arguments. +// _`Path<...>`_ or _`Query<...>`_ handler function arguments. /// /// _**Resole path argument types from tuple style handler arguments.**_ /// ```rust @@ -1984,7 +1984,7 @@ pub fn path(attr: TokenStream, item: TokenStream) -> TokenStream { /// /// * `paths(...)` List of method references having attribute [`#[utoipa::path]`][path] macro. /// * `components(schemas(...), responses(...))` Takes available _`component`_ configurations. Currently only -/// _`schema`_ and _`response`_ components are supported. +// _`schema`_ and _`response`_ components are supported. /// * `schemas(...)` List of [`ToSchema`][to_schema]s in OpenAPI schema. /// * `responses(...)` List of types that implement [`ToResponse`][to_response_trait]. /// * `modifiers(...)` List of items implementing [`Modify`][modify] trait for runtime OpenApi modification. @@ -2072,8 +2072,8 @@ pub fn path(attr: TokenStream, item: TokenStream) -> TokenStream { /// /// * `path = ...` Define mandatory path for nesting the [`OpenApi`][openapi_struct]. /// * `api = ...` Define mandatory path to struct that implements [`OpenApi`][openapi] trait. -/// The fully qualified path (_`path::to`_) will become the default _`tag`_ for the nested -/// `OpenApi` endpoints if provided. +// The fully qualified path (_`path::to`_) will become the default _`tag`_ for the nested +// `OpenApi` endpoints if provided. /// * `tags = [...]` Define optional tags what are appended to the existing list of tags. /// /// _**Example of nest definition**_ @@ -2278,13 +2278,12 @@ pub fn openapi(input: TokenStream) -> TokenStream { /// deriving `IntoParams`: /// /// * `names(...)` Define comma separated list of names for unnamed fields of struct used as a path parameter. -/// __Only__ supported on __unnamed structs__. +// __Only__ supported on __unnamed structs__. /// * `style = ...` Defines how all parameters are serialized by [`ParameterStyle`][style]. Default -/// values are based on _`parameter_in`_ attribute. +// values are based on _`parameter_in`_ attribute. /// * `parameter_in = ...` = Defines where the parameters of this field are used with a value from -/// [`openapi::path::ParameterIn`][in_enum]. There is no default value, if this attribute is not -/// supplied, then the value is determined by the `parameter_in_provider` in -/// [`IntoParams::into_params()`](trait.IntoParams.html#tymethod.into_params). +// [`openapi::path::ParameterIn`][in_enum]. There is no default value, if this attribute is not +// supplied, then the value is determined by the `parameter_in_provider` in [`IntoParams::into_params()`](trait.IntoParams.html#tymethod.into_params). /// * `rename_all = ...` Can be provided to alternatively to the serde's `rename_all` attribute. Effectively provides same functionality. /// /// Use `names` to define name for single unnamed argument. @@ -2339,13 +2338,11 @@ pub fn openapi(input: TokenStream) -> TokenStream { /// /// * `read_only` Defines property is only used in **read** operations *GET* but not in *POST,PUT,PATCH*. /// -/// * `xml(...)` Can be used to define [`Xml`][xml] object properties applicable to named fields. -/// See configuration options at xml attributes of [`ToSchema`][to_schema_xml] +/// * `xml(...)` Can be used to define [`Xml`][xml] object properties applicable to named fields. See configuration options at xml attributes of [`ToSchema`][to_schema_xml] /// /// * `nullable` Defines property is nullable (note this is different to non-required). /// -/// * `required = ...` Can be used to enforce required status for the parameter. [See -/// rules][derive@IntoParams#field-nullability-and-required-rules] +/// * `required = ...` Can be used to enforce required status for the parameter. [See rules][derive@IntoParams#field-nullability-and-required-rules] /// /// * `rename = ...` Can be provided to alternatively to the serde's `rename` attribute. Effectively provides same functionality. /// @@ -3432,7 +3429,7 @@ trait GenericsExt { fn get_generic_type_param_index(&self, type_tree: &TypeTree) -> Option; } -impl<'g> GenericsExt for &'g syn::Generics { +impl GenericsExt for &syn::Generics { fn get_generic_type_param_index(&self, type_tree: &TypeTree) -> Option { let ident = &type_tree .path @@ -3632,7 +3629,7 @@ impl AttributesExt for Vec { } } -impl<'a> AttributesExt for &'a [syn::Attribute] { +impl AttributesExt for &[syn::Attribute] { fn has_deprecated(&self) -> bool { self.iter().any(|attr| { matches!(attr.path().get_ident(), Some(ident) if &*ident.to_string() == "deprecated") diff --git a/utoipa-gen/src/openapi.rs b/utoipa-gen/src/openapi.rs index 8ba84abf..4be010fd 100644 --- a/utoipa-gen/src/openapi.rs +++ b/utoipa-gen/src/openapi.rs @@ -70,7 +70,7 @@ impl<'o> OpenApiAttr<'o> { } } -pub fn parse_openapi_attrs(attrs: &[Attribute]) -> Result, Error> { +pub fn parse_openapi_attrs(attrs: &[Attribute]) -> Result>, Error> { attrs .iter() .filter(|attribute| attribute.path().is_ident("openapi")) diff --git a/utoipa-gen/src/openapi/info.rs b/utoipa-gen/src/openapi/info.rs index 7922b7d1..9b9c18a4 100644 --- a/utoipa-gen/src/openapi/info.rs +++ b/utoipa-gen/src/openapi/info.rs @@ -347,10 +347,7 @@ impl TryFrom for Contact<'_> { ..Default::default() }) } else { - Err(io::Error::new( - io::ErrorKind::Other, - format!("invalid contact: {value}"), - )) + Err(io::Error::other(format!("invalid contact: {value}"))) } } } @@ -459,7 +456,7 @@ mod tests { _ => panic!(), } - assert!(matches!(info.terms_of_service, None)); + assert!(info.terms_of_service.is_none()); match info.license { Some(license) => { diff --git a/utoipa-gen/src/path.rs b/utoipa-gen/src/path.rs index 2b72a525..7e77c08b 100644 --- a/utoipa-gen/src/path.rs +++ b/utoipa-gen/src/path.rs @@ -266,10 +266,7 @@ impl FromStr for HttpMethod { "head" => Ok(Self::Head), "patch" => Ok(Self::Patch), "trace" => Ok(Self::Trace), - _ => Err(Error::new( - std::io::ErrorKind::Other, - HttpMethod::ERROR_MESSAGE, - )), + _ => Err(Error::other(HttpMethod::ERROR_MESSAGE)), } } } diff --git a/utoipa-gen/src/path/media_type.rs b/utoipa-gen/src/path/media_type.rs index ecdf7214..ba9093ff 100644 --- a/utoipa-gen/src/path/media_type.rs +++ b/utoipa-gen/src/path/media_type.rs @@ -229,7 +229,7 @@ impl Default for Schema<'_> { } impl Schema<'_> { - pub fn get_type_tree(&self) -> Result>>, Diagnostics> { + pub fn get_type_tree(&self) -> Result>>, Diagnostics> { match self { Self::Default(def) => def.get_type_tree(), Self::Ext(ext) => ext.get_type_tree(), @@ -417,7 +417,7 @@ pub struct ParsedType<'i> { impl ParsedType<'_> { /// Get's the underlying [`syn::Type`] as [`TypeTree`]. - fn to_type_tree(&self) -> Result { + fn to_type_tree(&self) -> Result, Diagnostics> { TypeTree::from_type(&self.ty) } } diff --git a/utoipa-gen/src/path/parameter.rs b/utoipa-gen/src/path/parameter.rs index 876b1318..8f17a6b0 100644 --- a/utoipa-gen/src/path/parameter.rs +++ b/utoipa-gen/src/path/parameter.rs @@ -45,7 +45,7 @@ use super::media_type::ParsedType; #[cfg_attr(feature = "debug", derive(Debug))] #[derive(PartialEq, Eq)] pub enum Parameter<'a> { - Value(ValueParameter<'a>), + Value(Box>), /// Identifier for a struct that implements `IntoParams` trait. IntoParamsIdent(IntoParamsIdentParameter<'a>), } @@ -94,7 +94,7 @@ impl ToTokensDiagnostics for Parameter<'_> { fn to_tokens(&self, tokens: &mut TokenStream) -> Result<(), Diagnostics> { match self { Parameter::Value(parameter) => { - let parameter = as_tokens_or_diagnostics!(parameter); + let parameter = as_tokens_or_diagnostics!(&**parameter); tokens.extend(quote! { .parameter(#parameter) }); } Parameter::IntoParamsIdent(IntoParamsIdentParameter { @@ -134,7 +134,7 @@ impl<'a> From> for Parameter<'a> { let option_is_nullable = parameter_in != ParameterIn::Query; - Self::Value(ValueParameter { + Self::Value(Box::new(ValueParameter { name: argument.name.unwrap_or_else(|| Cow::Owned(String::new())), parameter_in, parameter_schema: argument.type_tree.map(|type_tree| ParameterSchema { @@ -143,7 +143,7 @@ impl<'a> From> for Parameter<'a> { option_is_nullable, }), ..Default::default() - }) + })) } } @@ -442,9 +442,10 @@ impl PartialEq for IntoParamsIdentParameter<'_> { impl Eq for IntoParamsIdentParameter<'_> {} #[cfg_attr(feature = "debug", derive(Debug))] -#[derive(PartialEq, Eq, Clone, Copy)] +#[derive(PartialEq, Eq, Clone, Copy, Default)] pub enum ParameterIn { Query, + #[default] Path, Header, Cookie, @@ -465,12 +466,6 @@ impl Display for ParameterIn { } } -impl Default for ParameterIn { - fn default() -> Self { - Self::Path - } -} - impl Parse for ParameterIn { fn parse(input: ParseStream) -> syn::Result { fn expected_style() -> String { diff --git a/utoipa-gen/src/path/response.rs b/utoipa-gen/src/path/response.rs index 06f9a089..3210f216 100644 --- a/utoipa-gen/src/path/response.rs +++ b/utoipa-gen/src/path/response.rs @@ -33,7 +33,7 @@ pub enum Response<'r> { /// A type that implements `utoipa::IntoResponses`. IntoResponses(Cow<'r, TypePath>), /// The tuple definition of a response. - Tuple(ResponseTuple<'r>), + Tuple(Box>), } impl Parse for Response<'_> { @@ -673,11 +673,11 @@ struct ResponseStatus(TokenStream2); impl Parse for ResponseStatus { fn parse(input: ParseStream) -> syn::Result { - fn parse_lit_int(input: ParseStream) -> syn::Result> { + fn parse_lit_int(input: ParseStream<'_>) -> syn::Result> { input.parse::()?.base10_parse().map(Cow::Owned) } - fn parse_lit_str_status_range(input: ParseStream) -> syn::Result> { + fn parse_lit_str_status_range(input: ParseStream<'_>) -> syn::Result> { const VALID_STATUS_RANGES: [&str; 6] = ["default", "1XX", "2XX", "3XX", "4XX", "5XX"]; input @@ -762,7 +762,7 @@ impl ToTokensDiagnostics for Responses<'_> { } Response::Tuple(response) => { let code = &response.status_code; - let response = crate::as_tokens_or_diagnostics!(response); + let response = crate::as_tokens_or_diagnostics!(&**response); Ok(quote! { .response(#code, #response) }) } }) diff --git a/utoipa-gen/src/path/response/derive.rs b/utoipa-gen/src/path/response/derive.rs index 05e3e250..5c261677 100644 --- a/utoipa-gen/src/path/response/derive.rs +++ b/utoipa-gen/src/path/response/derive.rs @@ -190,7 +190,7 @@ impl ToTokensDiagnostics for IntoResponses { let ident = &self.ident; let (impl_generics, ty_generics, where_clause) = self.generics.split_for_impl(); - let responses = if responses.len() > 0 { + let responses = if !responses.is_empty() { Some(quote!( .responses_from_iter(#responses))) } else { None @@ -678,7 +678,7 @@ impl<'r> EnumResponse<'r> { Ok(Self(response_value.into())) } - fn parse_variant_attributes(variant: &Variant) -> Result { + fn parse_variant_attributes(variant: &Variant) -> Result, Diagnostics> { let variant_derive_response_value = DeriveToResponseValue::from_attributes(variant.attrs.as_slice())?; // named enum variant should not have field attributes diff --git a/utoipa-gen/tests/path_derive.rs b/utoipa-gen/tests/path_derive.rs index 2988362f..711d4b96 100644 --- a/utoipa-gen/tests/path_derive.rs +++ b/utoipa-gen/tests/path_derive.rs @@ -313,16 +313,6 @@ fn derive_path_with_extensions() { #[test] fn derive_path_with_datetime_format_query_parameter() { - #[derive(serde::Deserialize, utoipa::ToSchema)] - struct Since { - /// Some date - #[allow(dead_code)] - date: String, - /// Some time - #[allow(dead_code)] - time: String, - } - /// This is test operation /// /// This is long description for test operation @@ -354,16 +344,6 @@ fn derive_path_with_datetime_format_query_parameter() { #[test] fn derive_path_with_datetime_format_path_parameter() { - #[derive(serde::Deserialize, utoipa::ToSchema)] - struct Since { - /// Some date - #[allow(dead_code)] - date: String, - /// Some time - #[allow(dead_code)] - time: String, - } - /// This is test operation /// /// This is long description for test operation diff --git a/utoipa-swagger-ui/build.rs b/utoipa-swagger-ui/build.rs index 3e14f374..da5deb7f 100644 --- a/utoipa-swagger-ui/build.rs +++ b/utoipa-swagger-ui/build.rs @@ -9,14 +9,14 @@ use std::{ use regex::Regex; use zip::{result::ZipError, ZipArchive}; -/// the following env variables control the build process: -/// 1. SWAGGER_UI_DOWNLOAD_URL: -/// + the url from where to download the swagger-ui zip file if starts with http:// or https:// -/// + the file path from where to copy the swagger-ui zip file if starts with file:// -/// + default value is SWAGGER_UI_DOWNLOAD_URL_DEFAULT -/// + for other versions, check https://github.com/swagger-api/swagger-ui/tags -/// 2. SWAGGER_UI_OVERWRITE_FOLDER -/// + absolute path to a folder containing files to overwrite the default swagger-ui files +// the following env variables control the build process: +// 1. SWAGGER_UI_DOWNLOAD_URL: +// + the url from where to download the swagger-ui zip file if starts with http:// or https:// +// + the file path from where to copy the swagger-ui zip file if starts with file:// +// + default value is SWAGGER_UI_DOWNLOAD_URL_DEFAULT +// + for other versions, check https://github.com/swagger-api/swagger-ui/tags +// 2. SWAGGER_UI_OVERWRITE_FOLDER +// + absolute path to a folder containing files to overwrite the default swagger-ui files const SWAGGER_UI_DOWNLOAD_URL_DEFAULT: &str = "https://github.com/swagger-api/swagger-ui/archive/refs/tags/v5.17.14.zip"; @@ -147,7 +147,7 @@ impl SwaggerZip { } fn get_zip_archive(url: &str, target_dir: &str) -> SwaggerZip { - let zip_filename = url.split('/').last().unwrap().to_string(); + let zip_filename = url.split('/').next_back().unwrap().to_string(); #[allow(unused_mut)] let mut zip_path = [target_dir, &zip_filename].iter().collect::(); @@ -345,10 +345,9 @@ fn download_file_curl>(url: &str, target_dir: T) -> Result<(), Bo if status.success() { Ok(()) } else { - Err(std::io::Error::new( - io::ErrorKind::Other, - format!("curl download file exited with error status: {status}"), - )) + Err(std::io::Error::other(format!( + "curl download file exited with error status: {status}" + ))) } }) .map_err(|error| { diff --git a/utoipa-swagger-ui/src/actix.rs b/utoipa-swagger-ui/src/actix.rs index eb56b64c..65468c22 100644 --- a/utoipa-swagger-ui/src/actix.rs +++ b/utoipa-swagger-ui/src/actix.rs @@ -19,7 +19,11 @@ impl HttpServiceFactory for SwaggerUi { .urls .into_iter() .map(|(url, openapi)| { - register_api_doc_url_resource(url.url.as_ref(), ApiDoc::Utoipa(openapi), config); + register_api_doc_url_resource( + url.url.as_ref(), + ApiDoc::Utoipa(Box::new(openapi)), + config, + ); url }) .collect::>(); diff --git a/utoipa-swagger-ui/src/axum.rs b/utoipa-swagger-ui/src/axum.rs index 453044c5..9419dea4 100644 --- a/utoipa-swagger-ui/src/axum.rs +++ b/utoipa-swagger-ui/src/axum.rs @@ -28,7 +28,10 @@ where Vec::::with_capacity(urls_capacity + external_urls_capacity), ), |router_and_urls, (url, openapi)| { - add_api_doc_to_urls(router_and_urls, (url, Arc::new(ApiDoc::Utoipa(openapi)))) + add_api_doc_to_urls( + router_and_urls, + (url, Arc::new(ApiDoc::Utoipa(Box::new(openapi)))), + ) }, ); let (router, urls) = swagger_ui.external_urls.into_iter().fold( diff --git a/utoipa-swagger-ui/src/lib.rs b/utoipa-swagger-ui/src/lib.rs index 35e5bebe..39ebf2e8 100644 --- a/utoipa-swagger-ui/src/lib.rs +++ b/utoipa-swagger-ui/src/lib.rs @@ -74,8 +74,8 @@ //! * Current Swagger UI version: //! * [All available Swagger UI versions](https://github.com/swagger-api/swagger-ui/tags) //! -//! * `SWAGGER_UI_OVERWRITE_FOLDER`: Defines an _optional_ absolute path to a directory containing files -//! to overwrite the Swagger UI files. Typically you might want to overwrite `index.html`. +//! * `SWAGGER_UI_OVERWRITE_FOLDER`: Defines an _optional_ absolute path to a directory containing files +//! to overwrite the Swagger UI files. Typically you might want to overwrite `index.html`. //! //! # Examples //! @@ -704,7 +704,7 @@ impl<'a> Config<'a> { urls: urls .into_iter() .map(|mut url| { - if url.name == "" { + if url.name.is_empty() { url.name = Cow::Owned(String::from(&url.url[..])); url @@ -727,12 +727,12 @@ impl<'a> Config<'a> { Self { urls_primary_name: primary_name, - url: if url.name == "" { + url: if url.name.is_empty() { Some(url.url.to_string()) } else { None }, - urls: if url.name != "" { + urls: if !url.name.is_empty() { vec![url] } else { Vec::new() @@ -1512,7 +1512,7 @@ fn format_config(config: &Config, file: String) -> Result #[cfg(any(feature = "actix-web", feature = "rocket", feature = "axum"))] #[derive(Clone)] enum ApiDoc { - Utoipa(utoipa::openapi::OpenApi), + Utoipa(Box), Value(serde_json::Value), } diff --git a/utoipa-swagger-ui/src/rocket.rs b/utoipa-swagger-ui/src/rocket.rs index bd62e5e4..a0c32f00 100644 --- a/utoipa-swagger-ui/src/rocket.rs +++ b/utoipa-swagger-ui/src/rocket.rs @@ -24,7 +24,7 @@ impl From for Vec { let urls = swagger_ui .urls .into_iter() - .map(|(url, openapi)| (url, ApiDoc::Utoipa(openapi))) + .map(|(url, openapi)| (url, ApiDoc::Utoipa(Box::new(openapi)))) .chain( swagger_ui .external_urls @@ -82,10 +82,7 @@ impl Handler for ServeSwagger { let request_guard = request.guard::().await; match request_guard { request::Outcome::Success(BasicAuth { username, password }) - if username == basic_auth.username && password == basic_auth.password => - { - () - } + if username == basic_auth.username && password == basic_auth.password => {} _ => return Outcome::from(request, BasicAuthErrorResponse), } } diff --git a/utoipa/src/lib.rs b/utoipa/src/lib.rs index dbaa6a1d..ab6180b8 100644 --- a/utoipa/src/lib.rs +++ b/utoipa/src/lib.rs @@ -828,7 +828,7 @@ mod utoipa { /// impl PartialSchema for MyType { /// fn schema() -> RefOr { /// // ... impl schema generation here -/// RefOr::T(Schema::Object(ObjectBuilder::new().build())) +/// RefOr::T(Schema::Object(Box::new(ObjectBuilder::new().build()))) /// } /// } /// ``` @@ -845,13 +845,13 @@ mod utoipa { /// // // would be equal to manual implementation /// let number2 = RefOr::T( -/// Schema::Object( +/// Schema::Object(Box::new( /// ObjectBuilder::new() /// .schema_type(Type::Integer) /// .format(Some(SchemaFormat::KnownFormat(KnownFormat::Int64))) /// .build() /// ) -/// ); +/// )); /// # assert_eq!(serde_json::to_value(&number).unwrap(), serde_json::to_value(&number2).unwrap()); /// ``` /// diff --git a/utoipa/src/openapi/path.rs b/utoipa/src/openapi/path.rs index 79bac8af..4930388e 100644 --- a/utoipa/src/openapi/path.rs +++ b/utoipa/src/openapi/path.rs @@ -818,13 +818,14 @@ impl ParameterBuilder { } /// In definition of [`Parameter`]. -#[derive(Serialize, Deserialize, PartialEq, Eq, Clone)] +#[derive(Serialize, Deserialize, Default, PartialEq, Eq, Clone)] #[serde(rename_all = "lowercase")] #[cfg_attr(feature = "debug", derive(Debug))] pub enum ParameterIn { /// Declares that parameter is used as query parameter. Query, /// Declares that parameter is used as path parameter. + #[default] Path, /// Declares that parameter is used as header value. Header, @@ -832,12 +833,6 @@ pub enum ParameterIn { Cookie, } -impl Default for ParameterIn { - fn default() -> Self { - Self::Path - } -} - /// Defines how [`Parameter`] should be serialized. #[derive(Serialize, Deserialize, Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] diff --git a/utoipa/src/openapi/schema.rs b/utoipa/src/openapi/schema.rs index 859fb46c..32c7c390 100644 --- a/utoipa/src/openapi/schema.rs +++ b/utoipa/src/openapi/schema.rs @@ -36,12 +36,12 @@ macro_rules! to_array_builder { /// Can be used in places where an item can be serialized as `null`. This is used with unit type /// enum variants and tuple unit types. pub fn empty() -> Schema { - Schema::Object( + Schema::Object(Box::new( ObjectBuilder::new() .schema_type(SchemaType::AnyValue) .default(Some(serde_json::Value::Null)) .into(), - ) + )) } builder! { @@ -279,7 +279,7 @@ pub enum Schema { Array(Array), /// Defines object schema. Object is either `object` holding **properties** which are other [`Schema`]s /// or can be a field within the [`Object`]. - Object(Object), + Object(Box), /// Creates a _OneOf_ type [composite Object][composite] schema. This schema /// is used to map multiple schemas together where API endpoint could return any of them. /// [`Schema::OneOf`] is created form mixed enum where enum contains various variants. @@ -300,7 +300,7 @@ pub enum Schema { impl Default for Schema { fn default() -> Self { - Schema::Object(Object::default()) + Schema::Object(Box::default()) } } @@ -1100,7 +1100,7 @@ impl Object { impl From for Schema { fn from(s: Object) -> Self { - Self::Object(s) + Self::Object(Box::new(s)) } } @@ -1296,7 +1296,7 @@ component_from_builder!(ObjectBuilder); impl From for RefOr { fn from(builder: ObjectBuilder) -> Self { - Self::T(Schema::Object(builder.build())) + Self::T(Schema::Object(Box::new(builder.build()))) } } @@ -1338,7 +1338,7 @@ impl From> for AdditionalProperties { impl From for AdditionalProperties { fn from(value: ObjectBuilder) -> Self { - Self::RefOr(RefOr::T(Schema::Object(value.build()))) + Self::RefOr(RefOr::T(Schema::Object(Box::new(value.build())))) } } @@ -1485,7 +1485,7 @@ impl From for RefOr { impl Default for RefOr { fn default() -> Self { - Self::T(Schema::Object(Object::new())) + Self::T(Schema::Object(Box::new(Object::new()))) } } @@ -1493,7 +1493,7 @@ impl ToArray for RefOr {} impl From for RefOr { fn from(object: Object) -> Self { - Self::T(Schema::Object(object)) + Self::T(Schema::Object(Box::new(object))) } } @@ -2473,22 +2473,22 @@ mod tests { #[test] fn serialize_deserialize_array_within_ref_or_t_object_builder() { - let ref_or_schema = RefOr::T(Schema::Object( + let ref_or_schema = RefOr::T(Schema::Object(Box::new( ObjectBuilder::new() .property( "test", RefOr::T(Schema::Array( ArrayBuilder::new() - .items(RefOr::T(Schema::Object( + .items(RefOr::T(Schema::Object(Box::new( ObjectBuilder::new() .property("element", RefOr::Ref(Ref::new("#/test"))) .build(), - ))) + )))) .build(), )), ) .build(), - )); + ))); let json_str = serde_json::to_string(&ref_or_schema).expect(""); println!("----------------------------"); @@ -2505,7 +2505,7 @@ mod tests { #[test] fn serialize_deserialize_one_of_within_ref_or_t_object_builder() { - let ref_or_schema = RefOr::T(Schema::Object( + let ref_or_schema = RefOr::T(Schema::Object(Box::new( ObjectBuilder::new() .property( "test", @@ -2513,27 +2513,27 @@ mod tests { OneOfBuilder::new() .item(Schema::Array( ArrayBuilder::new() - .items(RefOr::T(Schema::Object( + .items(RefOr::T(Schema::Object(Box::new( ObjectBuilder::new() .property("element", RefOr::Ref(Ref::new("#/test"))) .build(), - ))) + )))) .build(), )) .item(Schema::Array( ArrayBuilder::new() - .items(RefOr::T(Schema::Object( + .items(RefOr::T(Schema::Object(Box::new( ObjectBuilder::new() .property("foobar", RefOr::Ref(Ref::new("#/foobar"))) .build(), - ))) + )))) .build(), )) .build(), )), ) .build(), - )); + ))); let json_str = serde_json::to_string(&ref_or_schema).expect(""); println!("----------------------------"); @@ -2550,7 +2550,7 @@ mod tests { #[test] fn serialize_deserialize_all_of_of_within_ref_or_t_object_builder() { - let ref_or_schema = RefOr::T(Schema::Object( + let ref_or_schema = RefOr::T(Schema::Object(Box::new( ObjectBuilder::new() .property( "test", @@ -2558,23 +2558,23 @@ mod tests { AllOfBuilder::new() .item(Schema::Array( ArrayBuilder::new() - .items(RefOr::T(Schema::Object( + .items(RefOr::T(Schema::Object(Box::new( ObjectBuilder::new() .property("element", RefOr::Ref(Ref::new("#/test"))) .build(), - ))) + )))) .build(), )) - .item(RefOr::T(Schema::Object( + .item(RefOr::T(Schema::Object(Box::new( ObjectBuilder::new() .property("foobar", RefOr::Ref(Ref::new("#/foobar"))) .build(), - ))) + )))) .build(), )), ) .build(), - )); + ))); let json_str = serde_json::to_string(&ref_or_schema).expect(""); println!("----------------------------"); @@ -2594,20 +2594,20 @@ mod tests { let a = OneOfBuilder::new() .item(Schema::Array( ArrayBuilder::new() - .items(RefOr::T(Schema::Object( + .items(RefOr::T(Schema::Object(Box::new( ObjectBuilder::new() .property("element", RefOr::Ref(Ref::new("#/test"))) .build(), - ))) + )))) .build(), )) .item(Schema::Array( ArrayBuilder::new() - .items(RefOr::T(Schema::Object( + .items(RefOr::T(Schema::Object(Box::new( ObjectBuilder::new() .property("foobar", RefOr::Ref(Ref::new("#/foobar"))) .build(), - ))) + )))) .build(), )) .build(); @@ -2623,7 +2623,7 @@ mod tests { #[test] fn serialize_deserialize_any_of_of_within_ref_or_t_object_builder() { - let ref_or_schema = RefOr::T(Schema::Object( + let ref_or_schema = RefOr::T(Schema::Object(Box::new( ObjectBuilder::new() .property( "test", @@ -2631,23 +2631,23 @@ mod tests { AnyOfBuilder::new() .item(Schema::Array( ArrayBuilder::new() - .items(RefOr::T(Schema::Object( + .items(RefOr::T(Schema::Object(Box::new( ObjectBuilder::new() .property("element", RefOr::Ref(Ref::new("#/test"))) .build(), - ))) + )))) .build(), )) - .item(RefOr::T(Schema::Object( + .item(RefOr::T(Schema::Object(Box::new( ObjectBuilder::new() .property("foobar", RefOr::Ref(Ref::new("#/foobar"))) .build(), - ))) + )))) .build(), )), ) .build(), - )); + ))); let json_str = serde_json::to_string(&ref_or_schema).expect(""); println!("----------------------------"); @@ -2666,11 +2666,11 @@ mod tests { fn serialize_deserialize_schema_array_ref_or_t() { let ref_or_schema = RefOr::T(Schema::Array( ArrayBuilder::new() - .items(RefOr::T(Schema::Object( + .items(RefOr::T(Schema::Object(Box::new( ObjectBuilder::new() .property("element", RefOr::Ref(Ref::new("#/test"))) .build(), - ))) + )))) .build(), )); @@ -2690,11 +2690,11 @@ mod tests { #[test] fn serialize_deserialize_schema_array_builder() { let ref_or_schema = ArrayBuilder::new() - .items(RefOr::T(Schema::Object( + .items(RefOr::T(Schema::Object(Box::new( ObjectBuilder::new() .property("element", RefOr::Ref(Ref::new("#/test"))) .build(), - ))) + )))) .build(); let json_str = serde_json::to_string(&ref_or_schema).expect(""); @@ -2712,7 +2712,7 @@ mod tests { #[test] fn serialize_deserialize_schema_with_additional_properties() { - let schema = Schema::Object( + let schema = Schema::Object(Box::new( ObjectBuilder::new() .property( "map", @@ -2720,7 +2720,7 @@ mod tests { .additional_properties(Some(AdditionalProperties::FreeForm(true))), ) .build(), - ); + )); let json_str = serde_json::to_string(&schema).unwrap(); println!("----------------------------"); @@ -2737,7 +2737,7 @@ mod tests { #[test] fn serialize_deserialize_schema_with_additional_properties_object() { - let schema = Schema::Object( + let schema = Schema::Object(Box::new( ObjectBuilder::new() .property( "map", @@ -2746,7 +2746,7 @@ mod tests { )), ) .build(), - ); + )); let json_str = serde_json::to_string(&schema).unwrap(); println!("----------------------------"); diff --git a/utoipa/src/openapi/security.rs b/utoipa/src/openapi/security.rs index 963ea98d..32989e95 100644 --- a/utoipa/src/openapi/security.rs +++ b/utoipa/src/openapi/security.rs @@ -352,11 +352,12 @@ impl HttpBuilder { /// Implements types according [RFC7235](https://datatracker.ietf.org/doc/html/rfc7235#section-5.1). /// /// Types are maintained at . -#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)] +#[derive(Serialize, Deserialize, Default, Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[serde(rename_all = "lowercase")] #[allow(missing_docs)] pub enum HttpAuthScheme { + #[default] Basic, Bearer, Digest, @@ -371,12 +372,6 @@ pub enum HttpAuthScheme { Vapid, } -impl Default for HttpAuthScheme { - fn default() -> Self { - Self::Basic - } -} - /// Open id connect [`SecurityScheme`]. #[non_exhaustive] #[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]