Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
5 changes: 1 addition & 4 deletions utoipa-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,10 +191,7 @@ impl<'c> Config<'c> {
}

fn get_out_dir() -> Option<String> {
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
Expand Down
2 changes: 1 addition & 1 deletion utoipa-gen/src/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ pub trait SynPathExt {
fn rewrite_path(&self) -> Result<syn::Path, Diagnostics>;
}

impl<'p> SynPathExt for &'p Path {
impl SynPathExt for &Path {
fn rewrite_path(&self) -> Result<syn::Path, Diagnostics> {
let last_segment = self
.segments
Expand Down
2 changes: 1 addition & 1 deletion utoipa-gen/src/component/features/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,7 @@ impl_feature! {

impl ValueType {
/// Create [`TypeTree`] from current [`syn::Type`].
pub fn as_type_tree(&self) -> Result<TypeTree, Diagnostics> {
pub fn as_type_tree(&self) -> Result<TypeTree<'_>, Diagnostics> {
TypeTree::from_type(&self.0)
}
}
Expand Down
1 change: 1 addition & 0 deletions utoipa-gen/src/component/features/validators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ impl Validator for IsString<'_> {
}
}

#[allow(dead_code)]
pub struct IsInteger<'a>(&'a SchemaType<'a>);

impl Validator for IsInteger<'_> {
Expand Down
7 changes: 5 additions & 2 deletions utoipa-gen/src/component/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ impl ToTokensDiagnostics for Schema<'_> {
enum SchemaVariant<'a> {
Named(NamedStructSchema),
Unnamed(UnnamedStructSchema),
Enum(EnumSchema<'a>),
Enum(Box<EnumSchema<'a>>),
Unit(UnitStructVariant),
}

Expand Down Expand Up @@ -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",
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 @@ -288,7 +288,7 @@ pub trait ArgumentResolver {
_: &'_ Punctuated<syn::FnArg, Comma>,
_: Option<Vec<MacroArg>>,
_: String,
) -> Result<Arguments, Diagnostics> {
) -> Result<Arguments<'_>, Diagnostics> {
Ok((None, None, None))
}
}
Expand Down Expand Up @@ -400,7 +400,7 @@ pub mod fn_arg {

pub fn get_fn_args(
fn_args: &Punctuated<syn::FnArg, Comma>,
) -> Result<impl Iterator<Item = FnArg>, Diagnostics> {
) -> Result<impl Iterator<Item = FnArg<'_>>, Diagnostics> {
fn_args
.iter()
.filter_map(|arg| {
Expand Down
2 changes: 1 addition & 1 deletion utoipa-gen/src/ext/actix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ impl ArgumentResolver for PathOperations {
fn_args: &Punctuated<syn::FnArg, Comma>,
macro_args: Option<Vec<MacroArg>>,
_: String,
) -> Result<Arguments, Diagnostics> {
) -> Result<Arguments<'_>, Diagnostics> {
let (into_params_args, value_args): (Vec<FnArg>, Vec<FnArg>) =
fn_arg::get_fn_args(fn_args)?.partition(fn_arg::is_into_params);

Expand Down
39 changes: 18 additions & 21 deletions utoipa-gen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ static CONFIG: once_cell::sync::Lazy<utoipa_config::Config> =
/// * `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].
Expand Down Expand Up @@ -200,7 +200,7 @@ static CONFIG: once_cell::sync::Lazy<utoipa_config::Config> =
/// * `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**.
Expand Down Expand Up @@ -487,7 +487,7 @@ static CONFIG: once_cell::sync::Lazy<utoipa_config::Config> =
/// 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.
Expand Down Expand Up @@ -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`].
Expand Down Expand Up @@ -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.
///
Expand Down Expand Up @@ -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).
///
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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**_
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
///
Expand Down Expand Up @@ -3432,7 +3429,7 @@ trait GenericsExt {
fn get_generic_type_param_index(&self, type_tree: &TypeTree) -> Option<usize>;
}

impl<'g> GenericsExt for &'g syn::Generics {
impl GenericsExt for &syn::Generics {
fn get_generic_type_param_index(&self, type_tree: &TypeTree) -> Option<usize> {
let ident = &type_tree
.path
Expand Down Expand Up @@ -3632,7 +3629,7 @@ impl AttributesExt for Vec<syn::Attribute> {
}
}

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")
Expand Down
2 changes: 1 addition & 1 deletion utoipa-gen/src/openapi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ impl<'o> OpenApiAttr<'o> {
}
}

pub fn parse_openapi_attrs(attrs: &[Attribute]) -> Result<Option<OpenApiAttr>, Error> {
pub fn parse_openapi_attrs(attrs: &[Attribute]) -> Result<Option<OpenApiAttr<'_>>, Error> {
attrs
.iter()
.filter(|attribute| attribute.path().is_ident("openapi"))
Expand Down
7 changes: 2 additions & 5 deletions utoipa-gen/src/openapi/info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,10 +347,7 @@ impl TryFrom<String> for Contact<'_> {
..Default::default()
})
} else {
Err(io::Error::new(
io::ErrorKind::Other,
format!("invalid contact: {value}"),
))
Err(io::Error::other(format!("invalid contact: {value}")))
}
}
}
Expand Down Expand Up @@ -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) => {
Expand Down
5 changes: 1 addition & 4 deletions utoipa-gen/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions utoipa-gen/src/path/media_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ impl Default for Schema<'_> {
}

impl Schema<'_> {
pub fn get_type_tree(&self) -> Result<Option<Cow<TypeTree<'_>>>, Diagnostics> {
pub fn get_type_tree(&self) -> Result<Option<Cow<'_, TypeTree<'_>>>, Diagnostics> {
match self {
Self::Default(def) => def.get_type_tree(),
Self::Ext(ext) => ext.get_type_tree(),
Expand Down Expand Up @@ -417,7 +417,7 @@ pub struct ParsedType<'i> {

impl ParsedType<'_> {
/// Get's the underlying [`syn::Type`] as [`TypeTree`].
fn to_type_tree(&self) -> Result<TypeTree, Diagnostics> {
fn to_type_tree(&self) -> Result<TypeTree<'_>, Diagnostics> {
TypeTree::from_type(&self.ty)
}
}
Expand Down
17 changes: 6 additions & 11 deletions utoipa-gen/src/path/parameter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ValueParameter<'a>>),
/// Identifier for a struct that implements `IntoParams` trait.
IntoParamsIdent(IntoParamsIdentParameter<'a>),
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -134,7 +134,7 @@ impl<'a> From<crate::ext::ValueArgument<'a>> 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 {
Expand All @@ -143,7 +143,7 @@ impl<'a> From<crate::ext::ValueArgument<'a>> for Parameter<'a> {
option_is_nullable,
}),
..Default::default()
})
}))
}
}

Expand Down Expand Up @@ -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,
Expand All @@ -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<Self> {
fn expected_style() -> String {
Expand Down
8 changes: 4 additions & 4 deletions utoipa-gen/src/path/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ResponseTuple<'r>>),
}

impl Parse for Response<'_> {
Expand Down Expand Up @@ -673,11 +673,11 @@ struct ResponseStatus(TokenStream2);

impl Parse for ResponseStatus {
fn parse(input: ParseStream) -> syn::Result<Self> {
fn parse_lit_int(input: ParseStream) -> syn::Result<Cow<'_, str>> {
fn parse_lit_int(input: ParseStream<'_>) -> syn::Result<Cow<'_, str>> {
input.parse::<LitInt>()?.base10_parse().map(Cow::Owned)
}

fn parse_lit_str_status_range(input: ParseStream) -> syn::Result<Cow<'_, str>> {
fn parse_lit_str_status_range(input: ParseStream<'_>) -> syn::Result<Cow<'_, str>> {
const VALID_STATUS_RANGES: [&str; 6] = ["default", "1XX", "2XX", "3XX", "4XX", "5XX"];

input
Expand Down Expand Up @@ -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) })
}
})
Expand Down
4 changes: 2 additions & 2 deletions utoipa-gen/src/path/response/derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -678,7 +678,7 @@ impl<'r> EnumResponse<'r> {
Ok(Self(response_value.into()))
}

fn parse_variant_attributes(variant: &Variant) -> Result<VariantAttributes, Diagnostics> {
fn parse_variant_attributes(variant: &Variant) -> Result<VariantAttributes<'_>, Diagnostics> {
let variant_derive_response_value =
DeriveToResponseValue::from_attributes(variant.attrs.as_slice())?;
// named enum variant should not have field attributes
Expand Down
Loading