1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-06-10 17:29:36 +00:00

code formatting cleanup

This commit is contained in:
Jon Lim 2023-09-13 22:45:37 -07:00
parent efe990dca5
commit ec4633a911
4 changed files with 69 additions and 43 deletions

View file

@ -2,6 +2,10 @@
## Unreleased ## Unreleased
## 4.2.3
- Add a scope macro that takes a path
## 4.2.2 ## 4.2.2
- Fix regression when declaring `wrap` attribute using an expression. - Fix regression when declaring `wrap` attribute using an expression.

View file

@ -328,4 +328,4 @@ pub fn test(_: TokenStream, item: TokenStream) -> TokenStream {
#[proc_macro_attribute] #[proc_macro_attribute]
pub fn scope(args: TokenStream, input: TokenStream) -> TokenStream { pub fn scope(args: TokenStream, input: TokenStream) -> TokenStream {
route::ScopeArgs::new(args, input).generate() route::ScopeArgs::new(args, input).generate()
} }

View file

@ -1,10 +1,9 @@
use std::collections::HashSet; use std::{collections::HashSet, fmt};
use actix_router::ResourceDef; use actix_router::ResourceDef;
use proc_macro::TokenStream; use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as TokenStream2}; use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::{quote, ToTokens, TokenStreamExt}; use quote::{quote, ToTokens, TokenStreamExt};
use std::fmt;
use syn::{punctuated::Punctuated, Ident, LitStr, Path, Token}; use syn::{punctuated::Punctuated, Ident, LitStr, Path, Token};
#[derive(Debug)] #[derive(Debug)]
@ -556,8 +555,8 @@ fn input_and_compile_error(mut item: TokenStream, err: syn::Error) -> TokenStrea
item item
} }
/// Implements scope proc macro /// Implements scope proc macro
/// ///
struct ScopeItems { struct ScopeItems {
handlers: Vec<String>, handlers: Vec<String>,
@ -570,23 +569,29 @@ impl ScopeItems {
for item in items { for item in items {
match item { match item {
syn::Item::Fn(ref fun) => { syn::Item::Fn(ref fun) => {
for attr in fun.attrs.iter() { for attr in fun.attrs.iter() {
for bound in attr.path().segments.iter() { for bound in attr.path().segments.iter() {
if bound.ident == "get" || bound.ident == "post" || bound.ident == "put" || bound.ident == "head" || bound.ident == "connect" || bound.ident == "options" || bound.ident == "trace" || bound.ident == "patch" || bound.ident == "delete" { if bound.ident == "get"
|| bound.ident == "post"
|| bound.ident == "put"
|| bound.ident == "head"
|| bound.ident == "connect"
|| bound.ident == "options"
|| bound.ident == "trace"
|| bound.ident == "patch"
|| bound.ident == "delete"
{
handlers.push(format!("{}", fun.sig.ident)); handlers.push(format!("{}", fun.sig.ident));
break; break;
} }
} }
} }
}, }
_ => continue, _ => continue,
} }
} }
Self { Self { handlers }
handlers,
}
} }
} }
@ -610,12 +615,14 @@ impl ScopeArgs {
let mut items = Vec::new(); let mut items = Vec::new();
match ast.expr.as_ref() { match ast.expr.as_ref() {
syn::Expr::Block(expr) => for item in expr.block.stmts.iter() { syn::Expr::Block(expr) => {
match item { for item in expr.block.stmts.iter() {
syn::Stmt::Item(ref item) => items.push(item.clone()), match item {
_ => continue, syn::Stmt::Item(ref item) => items.push(item.clone()),
_ => continue,
}
} }
}, }
_ => panic!("Scope should containt only code block"), _ => panic!("Scope should containt only code block"),
} }
@ -641,10 +648,9 @@ impl ScopeArgs {
match text.parse() { match text.parse() {
Ok(res) => res, Ok(res) => res,
Err(error) => panic!("Error: {:?}\nGenerated code: {}", error, text) Err(error) => panic!("Error: {:?}\nGenerated code: {}", error, text),
} }
} }
} }
impl fmt::Display for ScopeArgs { impl fmt::Display for ScopeArgs {
@ -655,22 +661,36 @@ impl fmt::Display for ScopeArgs {
let module_name = syn::Ident::new(&module_name, ast.ident.span()); let module_name = syn::Ident::new(&module_name, ast.ident.span());
let ast = match ast.expr.as_ref() { let ast = match ast.expr.as_ref() {
syn::Expr::Block(expr) => quote!(pub mod #module_name #expr), syn::Expr::Block(expr) => quote!(pub mod #module_name #expr),
_ => panic!("Unexpect non-block ast in scope macro") _ => panic!("Unexpect non-block ast in scope macro"),
}; };
writeln!(f, "{}\n", ast)?; writeln!(f, "{}\n", ast)?;
writeln!(f, "#[allow(non_camel_case_types)]")?; writeln!(f, "#[allow(non_camel_case_types)]")?;
writeln!(f, "struct {};\n", self.name)?; writeln!(f, "struct {};\n", self.name)?;
writeln!(f, "impl actix_web::dev::HttpServiceFactory for {} {{", self.name)?; writeln!(
writeln!(f, " fn register(self, __config: &mut actix_web::dev::AppService) {{")?; f,
write!(f, " let scope = actix_web::Scope::new(\"{}\")", self.path)?; "impl actix_web::dev::HttpServiceFactory for {} {{",
self.name
)?;
writeln!(
f,
" fn register(self, __config: &mut actix_web::dev::AppService) {{"
)?;
write!(
f,
" let scope = actix_web::Scope::new(\"{}\")",
self.path
)?;
for handler in self.scope_items.handlers.iter() { for handler in self.scope_items.handlers.iter() {
write!(f, ".service({}::{})", module_name, handler)?; write!(f, ".service({}::{})", module_name, handler)?;
} }
writeln!(f, ";\n")?; writeln!(f, ";\n")?;
writeln!(f, " actix_web::dev::HttpServiceFactory::register(scope, __config)")?; writeln!(
f,
" actix_web::dev::HttpServiceFactory::register(scope, __config)"
)?;
writeln!(f, " }}\n}}") writeln!(f, " }}\n}}")
} }
} }

View file

@ -11,7 +11,7 @@ use actix_web::{
web, App, Error, HttpRequest, HttpResponse, Responder, web, App, Error, HttpRequest, HttpResponse, Responder,
}; };
use actix_web_codegen::{ use actix_web_codegen::{
connect, delete, get, head, options, patch, post, put, route, routes, trace, scope connect, delete, get, head, options, patch, post, put, route, routes, scope, trace,
}; };
use futures_core::future::LocalBoxFuture; use futures_core::future::LocalBoxFuture;
@ -387,8 +387,10 @@ async fn test_wrap() {
#[scope("/test")] #[scope("/test")]
const mod_inner: () = { const mod_inner: () = {
use actix_web::{HttpResponse, HttpRequest, Responder, put, head, connect, options, trace, patch, delete, web }; use actix_web::{
use actix_web::web::Json; connect, delete, head, options, patch, put, trace, web, web::Json, HttpRequest,
HttpResponse, Responder,
};
#[actix_web::get("/test")] #[actix_web::get("/test")]
pub async fn test() -> impl Responder { pub async fn test() -> impl Responder {
@ -401,22 +403,22 @@ const mod_inner: () = {
let doubled = int_value * 2; let doubled = int_value * 2;
HttpResponse::Ok().body(format!("Twice value: {}", doubled)) HttpResponse::Ok().body(format!("Twice value: {}", doubled))
} }
#[actix_web::post("/test")] #[actix_web::post("/test")]
pub async fn test_post() -> impl Responder { pub async fn test_post() -> impl Responder {
HttpResponse::Ok().body(format!("post works")) HttpResponse::Ok().body(format!("post works"))
} }
#[put("/test")] #[put("/test")]
pub async fn test_put() -> impl Responder { pub async fn test_put() -> impl Responder {
HttpResponse::Ok().body(format!("put works")) HttpResponse::Ok().body(format!("put works"))
} }
#[head("/test")] #[head("/test")]
pub async fn test_head() -> impl Responder { pub async fn test_head() -> impl Responder {
HttpResponse::Ok().finish() HttpResponse::Ok().finish()
} }
#[connect("/test")] #[connect("/test")]
pub async fn test_connect() -> impl Responder { pub async fn test_connect() -> impl Responder {
HttpResponse::Ok().body("connect works") HttpResponse::Ok().body("connect works")
@ -441,7 +443,7 @@ const mod_inner: () = {
pub async fn test_delete() -> impl Responder { pub async fn test_delete() -> impl Responder {
HttpResponse::Ok().body("delete works") HttpResponse::Ok().body("delete works")
} }
pub fn mod_test2() -> impl actix_web::Responder { pub fn mod_test2() -> impl actix_web::Responder {
actix_web::HttpResponse::Ok().finish() actix_web::HttpResponse::Ok().finish()
} }
@ -464,7 +466,7 @@ async fn test_scope_get_param_async() {
let mut response = request.send().await.unwrap(); let mut response = request.send().await.unwrap();
let body = response.body().await.unwrap(); let body = response.body().await.unwrap();
let body_str = String::from_utf8(body.to_vec()).unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap();
assert_eq!(body_str, "Twice value: 8"); assert_eq!(body_str, "Twice value: 8");
} }
#[actix_rt::test] #[actix_rt::test]
@ -475,7 +477,7 @@ async fn test_scope_post_async() {
let mut response = request.send().await.unwrap(); let mut response = request.send().await.unwrap();
let body = response.body().await.unwrap(); let body = response.body().await.unwrap();
let body_str = String::from_utf8(body.to_vec()).unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap();
assert_eq!(body_str, "post works"); assert_eq!(body_str, "post works");
} }
#[actix_rt::test] #[actix_rt::test]
@ -486,7 +488,7 @@ async fn test_scope_put_async() {
let mut response = request.send().await.unwrap(); let mut response = request.send().await.unwrap();
let body = response.body().await.unwrap(); let body = response.body().await.unwrap();
let body_str = String::from_utf8(body.to_vec()).unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap();
assert_eq!(body_str, "put works"); assert_eq!(body_str, "put works");
} }
#[actix_rt::test] #[actix_rt::test]
@ -506,9 +508,9 @@ async fn test_scope_connect_async() {
let mut response = request.send().await.unwrap(); let mut response = request.send().await.unwrap();
let body = response.body().await.unwrap(); let body = response.body().await.unwrap();
let body_str = String::from_utf8(body.to_vec()).unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap();
assert_eq!(body_str, "connect works"); assert_eq!(body_str, "connect works");
} }
#[actix_rt::test] #[actix_rt::test]
async fn test_scope_options_async() { async fn test_scope_options_async() {
let srv = actix_test::start(|| App::new().service(mod_inner)); let srv = actix_test::start(|| App::new().service(mod_inner));
@ -517,7 +519,7 @@ async fn test_scope_options_async() {
let mut response = request.send().await.unwrap(); let mut response = request.send().await.unwrap();
let body = response.body().await.unwrap(); let body = response.body().await.unwrap();
let body_str = String::from_utf8(body.to_vec()).unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap();
assert_eq!(body_str, "options works"); assert_eq!(body_str, "options works");
} }
#[actix_rt::test] #[actix_rt::test]
@ -528,7 +530,7 @@ async fn test_scope_trace_async() {
let mut response = request.send().await.unwrap(); let mut response = request.send().await.unwrap();
let body = response.body().await.unwrap(); let body = response.body().await.unwrap();
let body_str = String::from_utf8(body.to_vec()).unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap();
assert!(body_str.contains("trace works")); assert!(body_str.contains("trace works"));
} }
#[actix_rt::test] #[actix_rt::test]
@ -539,7 +541,7 @@ async fn test_scope_patch_async() {
let mut response = request.send().await.unwrap(); let mut response = request.send().await.unwrap();
let body = response.body().await.unwrap(); let body = response.body().await.unwrap();
let body_str = String::from_utf8(body.to_vec()).unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap();
assert_eq!(body_str, "patch works"); assert_eq!(body_str, "patch works");
} }
#[actix_rt::test] #[actix_rt::test]
@ -550,5 +552,5 @@ async fn test_scope_delete_async() {
let mut response = request.send().await.unwrap(); let mut response = request.send().await.unwrap();
let body = response.body().await.unwrap(); let body = response.body().await.unwrap();
let body_str = String::from_utf8(body.to_vec()).unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap();
assert_eq!(body_str, "delete works"); assert_eq!(body_str, "delete works");
} }