Skip to content

Commit

Permalink
Set craft as optional feature (#921)
Browse files Browse the repository at this point in the history
* fix: Response doc

* Set craft as optional feature

* cargo clippy

* Format Rust code using rustfmt

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
  • Loading branch information
chrislearn and github-actions[bot] committed Sep 23, 2024
1 parent 678c9a6 commit 8004c1f
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 21 deletions.
3 changes: 3 additions & 0 deletions crates/core/src/http/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,8 @@ impl Response {
/// Useful when wanting to stream chunks from another thread.
///
/// # Example
///
/// ```
/// use salvo_core::prelude::*;
/// #[handler]
/// async fn hello(res: &mut Response) {
Expand All @@ -498,6 +500,7 @@ impl Response {
/// tx.send_data("Hello world").await.unwrap();
/// });
/// }
/// ```
#[inline]
pub fn channel(&mut self) -> BodySender {
let (sender, body) = ResBody::channel();
Expand Down
32 changes: 14 additions & 18 deletions crates/craft-macros/src/craft.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ fn take_method_macro(item_fn: &mut ImplItemFn) -> syn::Result<Option<Attribute>>
let mut new_attr: Option<Attribute> = None;
for (idx, attr) in &mut item_fn.attrs.iter().enumerate() {
if !(match attr.path().segments.last() {
Some(segment) => segment.ident.to_string() == "craft",
Some(segment) => segment.ident == "craft",
None => false,
}) {
continue;
Expand Down Expand Up @@ -63,24 +63,24 @@ fn take_method_macro(item_fn: &mut ImplItemFn) -> syn::Result<Option<Attribute>>
Ok(None)
}

enum MethodStyle {
NoSelf,
RefSelf,
ArcSelf,
enum FnReceiver {
None,
Ref,
Arc,
}

impl MethodStyle {
impl FnReceiver {
fn from_method(method: &ImplItemFn) -> syn::Result<Self> {
let Some(recv) = method.sig.receiver() else {
return Ok(Self::NoSelf);
return Ok(Self::None);
};
let ty = recv.ty.to_token_stream().to_string().replace(" ", "");
match ty.as_str() {
"&Self" => Ok(Self::RefSelf),
"Arc<Self>" | "&Arc<Self>" => Ok(Self::ArcSelf),
"&Self" => Ok(Self::Ref),
"Arc<Self>" | "&Arc<Self>" => Ok(Self::Arc),
_ => {
if ty.ends_with("::Arc<Self>") {
Ok(Self::ArcSelf)
Ok(Self::Arc)
} else {
Err(syn::Error::new_spanned(
method,
Expand All @@ -102,8 +102,8 @@ fn rewrite_method(self_ty: Box<Type>, method: &mut ImplItemFn) -> syn::Result<()
let method_name = method.sig.ident.clone();
let vis = method.vis.clone();
let mut attrs = method.attrs.clone();
let mut new_method: ImplItemFn = match MethodStyle::from_method(method)? {
MethodStyle::NoSelf => {
let mut new_method: ImplItemFn = match FnReceiver::from_method(method)? {
FnReceiver::None => {
method.attrs.push(macro_attr);
parse_quote! {
#vis fn #method_name() -> impl #handler {
Expand All @@ -116,12 +116,8 @@ fn rewrite_method(self_ty: Box<Type>, method: &mut ImplItemFn) -> syn::Result<()
}
style => {
let (receiver, output) = match style {
MethodStyle::RefSelf => {
(quote!(&self), quote!(::std::sync::Arc::new(self.clone())))
}
MethodStyle::ArcSelf => {
(quote!(self: &::std::sync::Arc<Self>), quote!(self.clone()))
}
FnReceiver::Ref => (quote!(&self), quote!(::std::sync::Arc::new(self.clone()))),
FnReceiver::Arc => (quote!(self: &::std::sync::Arc<Self>), quote!(self.clone())),
_ => unreachable!(),
};
method.sig.inputs[0] = FnArg::Receiver(parse_quote!(&self));
Expand Down
5 changes: 3 additions & 2 deletions crates/salvo/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ path = "src/lib.rs"

[features]
default = ["cookie", "fix-http1-request-uri", "server", "server-handle", "http1", "http2", "ring"]
full = ["cookie", "fix-http1-request-uri", "server", "server-handle", "http1", "http2", "http2-cleartext", "quinn", "rustls", "native-tls", "openssl", "unix", "acme", "socket2", "tower-compat", "anyhow", "eyre", "test", "affix-state", "basic-auth", "force-https", "jwt-auth", "catch-panic", "compression", "logging", "proxy", "concurrency-limiter", "rate-limiter", "sse", "trailing-slash", "timeout", "websocket", "request-id", "caching-headers", "cache", "cors", "csrf", "flash", "rate-limiter", "session", "serve-static", "otel", "oapi", "ring"]
full = ["cookie", "fix-http1-request-uri", "server", "server-handle", "http1", "http2", "http2-cleartext", "quinn", "rustls", "native-tls", "openssl", "unix", "acme", "socket2", "tower-compat", "anyhow", "eyre", "test", "affix-state", "basic-auth", "craft", "force-https", "jwt-auth", "catch-panic", "compression", "logging", "proxy", "concurrency-limiter", "rate-limiter", "sse", "trailing-slash", "timeout", "websocket", "request-id", "caching-headers", "cache", "cors", "csrf", "flash", "rate-limiter", "session", "serve-static", "otel", "oapi", "ring"]
cookie = ["salvo_core/cookie"]
fix-http1-request-uri = ["salvo_core/fix-http1-request-uri"]
server = ["salvo_core/server"]
Expand All @@ -45,6 +45,7 @@ eyre = ["salvo_core/eyre"]
test = ["salvo_core/test"]
affix-state = ["salvo_extra/affix-state"]
basic-auth = ["salvo_extra/basic-auth"]
craft = ["dep:salvo-craft"]
force-https = ["salvo_extra/force-https"]
jwt-auth = ["dep:salvo-jwt-auth"]
catch-panic = ["salvo_extra/catch-panic"]
Expand Down Expand Up @@ -87,7 +88,7 @@ salvo-serve-static = { workspace = true, features = ["full"], optional = true }
salvo-proxy = { workspace = true, features = ["full"], optional = true }
salvo-otel = { workspace = true, optional = true }
salvo-oapi = { workspace = true, features = ["full"], optional = true }
salvo-craft = { workspace = true }
salvo-craft = { workspace = true, optional = true }

[lints]
workspace = true
12 changes: 11 additions & 1 deletion crates/salvo/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
//! | `anyhow` | Integrate with the [`anyhow`](https://crates.io/crates/anyhow) crate | ❌ |
//! | `eyre` | Integrate with the [`eyre`](https://crates.io/crates/eyre) crate | ❌ |
//! | `affix-state` | Middleware for adding prefix and suffix to the request path | ❌ |
//! | `craft` | Generate handlers or endpoints with shared data | ❌ |
//! | `basic-auth` | Middleware for basic authentication | ❌ |
//! | `caching-headers` | Middleware for setting caching headers | ❌ |
//! | `catch-panic` | Middleware for catching panics | ❌ |
Expand Down Expand Up @@ -127,6 +128,11 @@ cfg_feature! {
#[doc(no_inline)]
pub use salvo_cors as cors;
}
cfg_feature! {
#![feature ="craft"]
// #[doc(no_inline)]
pub use salvo_craft as craft;
}
cfg_feature! {
#![feature ="csrf"]
#[doc(no_inline)]
Expand Down Expand Up @@ -196,6 +202,11 @@ pub mod prelude {
#![feature ="compression"]
pub use salvo_compression::{Compression, CompressionAlgo, CompressionLevel};
}
cfg_feature! {
#![feature ="craft"]
// #[doc(no_inline)]
pub use salvo_craft::craft;
}
cfg_feature! {
#![feature ="csrf"]
pub use salvo_csrf::CsrfDepotExt;
Expand Down Expand Up @@ -264,5 +275,4 @@ pub mod prelude {
pub use crate::oapi::redoc::ReDoc;
pub use crate::oapi::scalar::Scalar;
}
pub use salvo_craft::*;
}

0 comments on commit 8004c1f

Please sign in to comment.