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

Support servers in path macro #1293

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions utoipa-gen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ mod openapi;
mod path;
mod schema_type;
mod security_requirement;
mod server;

use crate::path::{Path, PathAttr};

Expand Down
146 changes: 2 additions & 144 deletions utoipa-gen/src/openapi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use syn::{
punctuated::Punctuated,
spanned::Spanned,
token::{And, Comma},
Attribute, Error, ExprPath, LitStr, Token, TypePath,
Attribute, Error, ExprPath, Token, TypePath,
};

use proc_macro2::TokenStream;
Expand All @@ -17,6 +17,7 @@ use crate::{
component::{features::Feature, ComponentSchema, Container, TypeTree},
parse_utils,
security_requirement::SecurityRequirementsAttr,
server::Server,
Array, Diagnostics, ExternalDocs, ToTokensDiagnostics,
};
use crate::{path, OptionExt};
Expand Down Expand Up @@ -272,149 +273,6 @@ impl ToTokens for Tag {
tokens.extend(quote! { .build() })
}
}

// (url = "http:://url", description = "description", variables(...))
#[derive(Default)]
#[cfg_attr(feature = "debug", derive(Debug))]
pub struct Server {
url: String,
description: Option<String>,
variables: Punctuated<ServerVariable, Comma>,
}

impl Parse for Server {
fn parse(input: ParseStream) -> syn::Result<Self> {
let server_stream;
parenthesized!(server_stream in input);
let mut server = Server::default();
while !server_stream.is_empty() {
let ident = server_stream.parse::<Ident>()?;
let attribute_name = &*ident.to_string();

match attribute_name {
"url" => {
server.url = parse_utils::parse_next(&server_stream, || server_stream.parse::<LitStr>())?.value()
}
"description" => {
server.description =
Some(parse_utils::parse_next(&server_stream, || server_stream.parse::<LitStr>())?.value())
}
"variables" => {
server.variables = parse_utils::parse_comma_separated_within_parenthesis(&server_stream)?
}
_ => {
return Err(Error::new(ident.span(), format!("unexpected attribute: {attribute_name}, expected one of: url, description, variables")))
}
}

if !server_stream.is_empty() {
server_stream.parse::<Comma>()?;
}
}

Ok(server)
}
}

impl ToTokens for Server {
fn to_tokens(&self, tokens: &mut TokenStream) {
let url = &self.url;
let description = &self
.description
.as_ref()
.map(|description| quote! { .description(Some(#description)) });

let parameters = self
.variables
.iter()
.map(|variable| {
let name = &variable.name;
let default_value = &variable.default;
let description = &variable
.description
.as_ref()
.map(|description| quote! { .description(Some(#description)) });
let enum_values = &variable.enum_values.as_ref().map(|enum_values| {
let enum_values = enum_values.iter().collect::<Array<&LitStr>>();

quote! { .enum_values(Some(#enum_values)) }
});

quote! {
.parameter(#name, utoipa::openapi::server::ServerVariableBuilder::new()
.default_value(#default_value)
#description
#enum_values
)
}
})
.collect::<TokenStream>();

tokens.extend(quote! {
utoipa::openapi::server::ServerBuilder::new()
.url(#url)
#description
#parameters
.build()
})
}
}

// ("username" = (default = "demo", description = "This is default username for the API")),
// ("port" = (enum_values = (8080, 5000, 4545)))
#[derive(Default)]
#[cfg_attr(feature = "debug", derive(Debug))]
struct ServerVariable {
name: String,
default: String,
description: Option<String>,
enum_values: Option<Punctuated<LitStr, Comma>>,
}

impl Parse for ServerVariable {
fn parse(input: ParseStream) -> syn::Result<Self> {
let variable_stream;
parenthesized!(variable_stream in input);
let mut server_variable = ServerVariable {
name: variable_stream.parse::<LitStr>()?.value(),
..ServerVariable::default()
};

variable_stream.parse::<Token![=]>()?;
let content;
parenthesized!(content in variable_stream);

while !content.is_empty() {
let ident = content.parse::<Ident>()?;
let attribute_name = &*ident.to_string();

match attribute_name {
"default" => {
server_variable.default =
parse_utils::parse_next(&content, || content.parse::<LitStr>())?.value()
}
"description" => {
server_variable.description =
Some(parse_utils::parse_next(&content, || content.parse::<LitStr>())?.value())
}
"enum_values" => {
server_variable.enum_values =
Some(parse_utils::parse_comma_separated_within_parenthesis(&content)?)
}
_ => {
return Err(Error::new(ident.span(), format!( "unexpected attribute: {attribute_name}, expected one of: default, description, enum_values")))
}
}

if !content.is_empty() {
content.parse::<Comma>()?;
}
}

Ok(server_variable)
}
}

pub(crate) struct OpenApi<'o>(pub Option<OpenApiAttr<'o>>, pub Ident);

impl OpenApi<'_> {
Expand Down
19 changes: 19 additions & 0 deletions utoipa-gen/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use syn::{parenthesized, parse::Parse, Token};
use syn::{Expr, ExprLit, Lit, LitStr};

use crate::component::{ComponentSchema, GenericType, TypeTree};
use crate::server::Server;
use crate::{
as_tokens_or_diagnostics, parse_utils, Deprecated, Diagnostics, OptionExt, ToTokensDiagnostics,
};
Expand Down Expand Up @@ -53,6 +54,7 @@ pub struct PathAttr<'p> {
impl_for: Option<Ident>,
description: Option<parse_utils::LitStrOrExpr>,
summary: Option<parse_utils::LitStrOrExpr>,
servers: Vec<Server>,
}

impl<'p> PathAttr<'p> {
Expand Down Expand Up @@ -182,6 +184,14 @@ impl Parse for PathAttr<'_> {
"summary" => {
path_attr.summary = Some(parse_utils::parse_next_literal_str_or_expr(input)?)
}
"servers" => {
let servers;
syn::parenthesized!(servers in input);
path_attr.servers =
Punctuated::<Server, Token![,]>::parse_terminated(&servers)?
.into_iter()
.collect();
}
_ => {
if let Some(path_operation) =
attribute_name.parse::<HttpMethod>().into_iter().next()
Expand Down Expand Up @@ -467,6 +477,7 @@ impl<'p> ToTokensDiagnostics for Path<'p> {
request_body: self.path_attr.request_body.as_ref(),
responses: self.path_attr.responses.as_ref(),
security: self.path_attr.security.as_ref(),
servers: self.path_attr.servers.as_ref(),
};
let operation = as_tokens_or_diagnostics!(&operation);

Expand Down Expand Up @@ -625,6 +636,7 @@ struct Operation<'a> {
request_body: Option<&'a RequestBodyAttr<'a>>,
responses: &'a Vec<Response<'a>>,
security: Option<&'a Array<'a, SecurityRequirementsAttr>>,
servers: &'a Vec<Server>,
}

impl ToTokensDiagnostics for Operation<'_> {
Expand Down Expand Up @@ -653,6 +665,13 @@ impl ToTokensDiagnostics for Operation<'_> {
.operation_id(Some(#operation_id))
});

if !self.servers.is_empty() {
let servers = self.servers.iter().collect::<Array<_>>();
tokens.extend(quote! {
.servers(Some(#servers))
})
}

if self.deprecated {
let deprecated: Deprecated = self.deprecated.into();
tokens.extend(quote!( .deprecated(Some(#deprecated))))
Expand Down
2 changes: 1 addition & 1 deletion utoipa-gen/src/path/response/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use syn::punctuated::Punctuated;
use syn::token::Comma;
use syn::{Ident, Token};

use crate::openapi::Server;
use crate::server::Server;
use crate::{parse_utils, AnyValue};

/// ("name" = (link))
Expand Down
Loading
Loading