From 880550a78f2e0b20f095fcfe15b82fb479d792a4 Mon Sep 17 00:00:00 2001 From: simonsan <14062932+simonsan@users.noreply.github.com> Date: Thu, 14 Nov 2024 07:34:36 +0100 Subject: [PATCH] fix clippy lints Signed-off-by: simonsan <14062932+simonsan@users.noreply.github.com> --- src/acl.rs | 8 ++--- src/application.rs | 7 ++-- src/auth.rs | 13 +++----- src/commands.rs | 8 ++--- src/commands/auth.rs | 2 +- src/commands/serve.rs | 6 ++-- src/config.rs | 8 ++--- src/error.rs | 62 ++++++++++++++++------------------- src/handlers/access_check.rs | 2 +- src/handlers/file_config.rs | 16 ++++----- src/handlers/file_exchange.rs | 31 +++++++++--------- src/handlers/file_helpers.rs | 2 +- src/handlers/file_length.rs | 2 +- src/handlers/files_list.rs | 16 ++++----- src/handlers/repository.rs | 12 +++---- src/htpasswd.rs | 12 +++---- src/lib.rs | 4 +-- src/log.rs | 2 +- src/prelude.rs | 2 +- src/storage.rs | 13 ++++---- src/test_helpers.rs | 2 +- src/typed_path.rs | 2 +- tests/acceptance.rs | 2 +- 23 files changed, 110 insertions(+), 124 deletions(-) diff --git a/src/acl.rs b/src/acl.rs index 91530e3..154283e 100644 --- a/src/acl.rs +++ b/src/acl.rs @@ -21,7 +21,7 @@ pub fn init_acl(acl: Acl) -> AppResult<()> { /// // IMPORTANT: The order of the variants is important, as it is used // to determine the access level! Don't change it! -#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize, Copy)] +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Serialize, Deserialize, Copy)] pub enum AccessType { /// No access NoAccess, @@ -205,9 +205,7 @@ impl AclChecker for Acl { access_type }; - if let Some(repo_acl) = self.repos.get(path) { - matches!(repo_acl.get(user), Some(user_access) if user_access >= &access) - } else { + self.repos.get(path).map_or_else(|| { let is_user_path = user == path; let is_not_private_repo = !self.private_repo; let is_not_modify_access = access != AccessType::Modify; @@ -220,7 +218,7 @@ impl AclChecker for Acl { // If the user is the path, and the repo is not private, or the user has modify access // or the repo is not append only, then allow the access (is_user_path || is_not_private_repo) && (is_not_modify_access || is_not_append_only) - } + }, |repo_acl| matches!(repo_acl.get(user), Some(user_access) if user_access >= &access)) } } diff --git a/src/application.rs b/src/application.rs index a71b03d..797d699 100644 --- a/src/application.rs +++ b/src/application.rs @@ -1,4 +1,4 @@ -//! RusticServer Abscissa Application +//! `RusticServer` Abscissa Application use crate::{commands::EntryPoint, config::RusticServerConfig}; use abscissa_core::{ @@ -11,7 +11,7 @@ use abscissa_tokio::TokioComponent; /// Application state pub static RUSTIC_SERVER_APP: AppCell = AppCell::new(); -/// RusticServer Application +/// `RusticServer` Application #[derive(Debug)] pub struct RusticServerApp { /// Application configuration. @@ -75,8 +75,7 @@ impl Application for RusticServerApp { /// possible. fn after_config(&mut self, config: Self::Cfg) -> Result<(), FrameworkError> { // Configure components - let mut components = self.state.components_mut(); - components.after_config(&config)?; + self.state.components_mut().after_config(&config)?; self.config.set_once(config); Ok(()) } diff --git a/src/auth.rs b/src/auth.rs index 29d92c8..77df8b3 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -59,12 +59,7 @@ impl Auth { let user = user.into(); let passwd = passwd.into(); - match &self.users { - Some(users) => { - matches!(users.get(&user), Some(passwd_data) if htpasswd_verify::Htpasswd::from(passwd_data.to_string().borrow()).check(user, passwd)) - } - None => true, - } + self.users.as_ref().map_or(true, |users| matches!(users.get(&user), Some(passwd_data) if htpasswd_verify::Htpasswd::from(passwd_data.to_string().borrow()).check(user, passwd))) } } @@ -90,7 +85,7 @@ impl FromRequestParts for AuthFromRequest { return match auth_result { Ok(auth) => { let AuthBasic((user, passw)) = auth; - let password = passw.unwrap_or_else(|| "".to_string()); + let password = passw.unwrap_or_else(String::new); if checker.verify(user.as_str(), password.as_str()) { Ok(Self { user, @@ -101,11 +96,11 @@ impl FromRequestParts for AuthFromRequest { } } Err(_) => { - let user = "".to_string(); + let user = String::new(); if checker.verify("", "") { return Ok(Self { user, - _password: "".to_string().into(), + _password: String::new().into(), }); } Err(ApiErrorKind::AuthenticationHeaderError) diff --git a/src/commands.rs b/src/commands.rs index c0892e1..74352bf 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -1,4 +1,4 @@ -//! RusticServer Subcommands +//! `RusticServer` Subcommands //! //! This is where you specify the subcommands of your application. //! @@ -24,10 +24,10 @@ use clap::builder::{ }; use std::path::PathBuf; -/// RusticServer Configuration Filename +/// `RusticServer` Configuration Filename pub const CONFIG_FILE: &str = "rustic_server.toml"; -/// RusticServer Subcommands +/// `RusticServer` Subcommands /// Subcommands need to be listed in an enum. #[derive(clap::Parser, Command, Debug, Runnable)] pub enum RusticServerCmd { @@ -65,7 +65,7 @@ pub struct EntryPoint { impl Runnable for EntryPoint { fn run(&self) { - self.cmd.run() + self.cmd.run(); } } diff --git a/src/commands/auth.rs b/src/commands/auth.rs index a445fc8..7dd81b7 100644 --- a/src/commands/auth.rs +++ b/src/commands/auth.rs @@ -188,7 +188,7 @@ fn delete(arg: &DelArg) -> Result<()> { println!( "Could not find a user with name {}. No changes were made.", arg.user.as_str() - ) + ); }; Ok(()) } diff --git a/src/commands/serve.rs b/src/commands/serve.rs index 9995fa2..f3482c0 100644 --- a/src/commands/serve.rs +++ b/src/commands/serve.rs @@ -76,13 +76,13 @@ impl ServeCmd { if !data_dir.exists() { debug!("Creating data directory: {:?}", data_dir); - std::fs::create_dir_all(&data_dir).map_err(|err| { + std::fs::create_dir_all(data_dir).map_err(|err| { ErrorKind::GeneralStorageError .context(format!("Could not create data directory: {}", err)) })?; } - let storage = LocalStorage::try_new(&data_dir).map_err(|err| { + let storage = LocalStorage::try_new(data_dir).map_err(|err| { ErrorKind::GeneralStorageError.context(format!("Could not create storage: {}", err)) })?; @@ -108,7 +108,7 @@ impl ServeCmd { info!("[serve] Starting web server ..."); - let _ = tokio::spawn(async move { + _ = tokio::spawn(async move { tokio::signal::ctrl_c().await.unwrap(); info!("[serve] Shutting down ..."); RUSTIC_SERVER_APP.shutdown(Shutdown::Graceful); diff --git a/src/config.rs b/src/config.rs index d0073ee..6aaf84a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,4 +1,4 @@ -//! RusticServer Config +//! `RusticServer` Config //! //! See instructions in `commands.rs` to specify the path to your //! application's configuration file and/or command-line options @@ -15,7 +15,7 @@ use serde::{Deserialize, Serialize}; use crate::error::{AppResult, ErrorKind}; -/// RusticServer Configuration +/// `RusticServer` Configuration #[derive(Clone, Debug, Deserialize, Serialize, Default, Merge, Parser)] #[serde(deny_unknown_fields, rename_all = "kebab-case", default)] pub struct RusticServerConfig { @@ -78,7 +78,7 @@ pub struct LogSettings { } impl LogSettings { - pub fn is_disabled(&self) -> bool { + pub const fn is_disabled(&self) -> bool { self.log_file.is_none() } } @@ -152,7 +152,7 @@ impl HtpasswdSettings { }) } - pub fn is_disabled(&self) -> bool { + pub const fn is_disabled(&self) -> bool { self.disable_auth } } diff --git a/src/error.rs b/src/error.rs index c9d3f63..02e262d 100644 --- a/src/error.rs +++ b/src/error.rs @@ -94,104 +94,100 @@ pub enum ApiErrorKind { impl IntoResponse for ApiErrorKind { fn into_response(self) -> Response { let response = match self { - ApiErrorKind::InvalidApiVersion(err) => ( + Self::InvalidApiVersion(err) => ( StatusCode::BAD_REQUEST, format!("Invalid API version: {err}"), ), - ApiErrorKind::InternalError(err) => ( + Self::InternalError(err) => ( StatusCode::INTERNAL_SERVER_ERROR, format!("Internal server error: {}", err), ), - ApiErrorKind::BadRequest(err) => ( + Self::BadRequest(err) => ( StatusCode::BAD_REQUEST, format!("Internal server error: {}", err), ), - ApiErrorKind::FilenameNotAllowed(filename) => ( + Self::FilenameNotAllowed(filename) => ( StatusCode::FORBIDDEN, format!("filename {filename} not allowed"), ), - ApiErrorKind::AmbiguousPath(path) => ( + Self::AmbiguousPath(path) => ( StatusCode::FORBIDDEN, format!("path {path} is ambiguous with internal types and not allowed"), ), - ApiErrorKind::PathNotAllowed(path) => { + Self::PathNotAllowed(path) => { (StatusCode::FORBIDDEN, format!("path {path} not allowed")) } - ApiErrorKind::NonUnicodePath(path) => ( + Self::NonUnicodePath(path) => ( StatusCode::BAD_REQUEST, format!("path {path} is not valid unicode"), ), - ApiErrorKind::InvalidPath(path) => { + Self::InvalidPath(path) => { (StatusCode::BAD_REQUEST, format!("path {path} is not valid")) } - ApiErrorKind::CreatingDirectoryFailed(err) => ( + Self::CreatingDirectoryFailed(err) => ( StatusCode::INTERNAL_SERVER_ERROR, format!("error creating dir: {:?}", err), ), - ApiErrorKind::NotImplemented => ( + Self::NotImplemented => ( StatusCode::NOT_IMPLEMENTED, "not yet implemented".to_string(), ), - ApiErrorKind::FileNotFound(path) => { - (StatusCode::NOT_FOUND, format!("file not found: {path}")) - } - ApiErrorKind::GettingFileMetadataFailed(err) => ( + Self::FileNotFound(path) => (StatusCode::NOT_FOUND, format!("file not found: {path}")), + Self::GettingFileMetadataFailed(err) => ( StatusCode::INTERNAL_SERVER_ERROR, format!("error getting file metadata: {err}"), ), - ApiErrorKind::RangeNotValid => (StatusCode::BAD_REQUEST, "range not valid".to_string()), - ApiErrorKind::SeekingFileFailed => ( + Self::RangeNotValid => (StatusCode::BAD_REQUEST, "range not valid".to_string()), + Self::SeekingFileFailed => ( StatusCode::INTERNAL_SERVER_ERROR, "error seeking file".to_string(), ), - ApiErrorKind::MultipartRangeNotImplemented => ( + Self::MultipartRangeNotImplemented => ( StatusCode::NOT_IMPLEMENTED, "multipart range not implemented".to_string(), ), - ApiErrorKind::ConversionToU64Failed => ( + Self::ConversionToU64Failed => ( StatusCode::INTERNAL_SERVER_ERROR, "error converting length to u64".to_string(), ), - ApiErrorKind::OpeningFileFailed(err) => ( + Self::OpeningFileFailed(err) => ( StatusCode::INTERNAL_SERVER_ERROR, format!("error opening file: {err}"), ), - ApiErrorKind::WritingToFileFailed(err) => ( + Self::WritingToFileFailed(err) => ( StatusCode::INTERNAL_SERVER_ERROR, format!("error writing file: {err}"), ), - ApiErrorKind::FinalizingFileFailed(err) => ( + Self::FinalizingFileFailed(err) => ( StatusCode::INTERNAL_SERVER_ERROR, format!("error finalizing file: {err}"), ), - ApiErrorKind::GettingFileHandleFailed => ( + Self::GettingFileHandleFailed => ( StatusCode::INTERNAL_SERVER_ERROR, "error getting file handle".to_string(), ), - ApiErrorKind::RemovingFileFailed(err) => ( + Self::RemovingFileFailed(err) => ( StatusCode::INTERNAL_SERVER_ERROR, format!("error removing file: {err}"), ), - ApiErrorKind::GeneralRange => { - (StatusCode::INTERNAL_SERVER_ERROR, "range error".to_string()) - } - ApiErrorKind::ReadingFromStreamFailed => ( + Self::GeneralRange => (StatusCode::INTERNAL_SERVER_ERROR, "range error".to_string()), + Self::ReadingFromStreamFailed => ( StatusCode::INTERNAL_SERVER_ERROR, "error reading from stream".to_string(), ), - ApiErrorKind::RemovingRepositoryFailed(err) => ( + Self::RemovingRepositoryFailed(err) => ( StatusCode::INTERNAL_SERVER_ERROR, format!("error removing repository folder: {:?}", err), ), - ApiErrorKind::AuthenticationHeaderError => ( + Self::AuthenticationHeaderError => ( StatusCode::FORBIDDEN, "Bad authentication header".to_string(), ), - ApiErrorKind::UserAuthenticationError(err) => ( + Self::UserAuthenticationError(err) => ( StatusCode::FORBIDDEN, format!("Failed to authenticate user: {:?}", err), ), - ApiErrorKind::GeneralStorageError(err) => ( + Self::GeneralStorageError(err) => ( StatusCode::INTERNAL_SERVER_ERROR, format!("Storage error: {:?}", err), ), @@ -203,7 +199,7 @@ impl IntoResponse for ApiErrorKind { impl ErrorKind { /// Create an error context from this error - pub fn context(self, source: impl Into) -> Context { + pub fn context(self, source: impl Into) -> Context { Context::new(self, Some(source.into())) } } @@ -240,7 +236,7 @@ impl From for Error { impl From> for Error { fn from(context: Context) -> Self { - Error(Box::new(context)) + Self(Box::new(context)) } } diff --git a/src/handlers/access_check.rs b/src/handlers/access_check.rs index 5274d33..13ebc80 100644 --- a/src/handlers/access_check.rs +++ b/src/handlers/access_check.rs @@ -12,7 +12,7 @@ use crate::{ typed_path::TpeKind, }; -pub(crate) fn check_auth_and_acl( +pub fn check_auth_and_acl( user: String, tpe: impl Into>, path: &Path, diff --git a/src/handlers/file_config.rs b/src/handlers/file_config.rs index dd7c4aa..132cab5 100644 --- a/src/handlers/file_config.rs +++ b/src/handlers/file_config.rs @@ -21,7 +21,7 @@ use crate::{ /// has_config /// Interface: HEAD {repo}/config #[debug_handler] -pub(crate) async fn has_config( +pub async fn has_config( RepositoryConfigPath { repo }: RepositoryConfigPath, AuthFromRequest { user, .. }: AuthFromRequest, ) -> ApiResult { @@ -53,9 +53,9 @@ pub(crate) async fn has_config( } } -/// get_config +/// `get_config` /// Interface: GET {repo}/config -pub(crate) async fn get_config( +pub async fn get_config( path: P, auth: AuthFromRequest, range: Option>, @@ -81,9 +81,9 @@ pub(crate) async fn get_config( Ok(Ranged::new(range, body).into_response()) } -/// add_config +/// `add_config` /// Interface: POST {repo}/config -pub(crate) async fn add_config( +pub async fn add_config( path: P, auth: AuthFromRequest, request: Request, @@ -92,17 +92,17 @@ pub(crate) async fn add_config( let repo = path.repo().unwrap(); tracing::debug!("[add_config] repository path: {repo}, tpe: {tpe}"); let path = PathBuf::from(&repo); - let file = get_save_file(auth.user, path, tpe, None).await?; + let file = get_save_file(auth.user, path, Some(tpe), None).await?; let stream = request.into_body().into_data_stream(); let _ = save_body(file, stream).await?; Ok(()) } -/// delete_config +/// `delete_config` /// Interface: DELETE {repo}/config #[allow(dead_code)] -pub(crate) async fn delete_config( +pub async fn delete_config( path: P, auth: AuthFromRequest, ) -> ApiResult { diff --git a/src/handlers/file_exchange.rs b/src/handlers/file_exchange.rs index fbf1f37..7b51a69 100644 --- a/src/handlers/file_exchange.rs +++ b/src/handlers/file_exchange.rs @@ -21,11 +21,11 @@ use crate::{ typed_path::{PathParts, TpeKind}, }; -/// add_file +/// `add_file` /// Interface: POST {path}/{type}/{name} -/// Background info: https://github.com/tokio-rs/axum/blob/main/examples/stream-to-file/src/main.rs -/// Future on ranges: https://www.rfc-editor.org/rfc/rfc9110.html#name-partial-put -pub(crate) async fn add_file( +/// Background info: +/// Future on ranges: +pub async fn add_file( path: P, auth: AuthFromRequest, request: Request, @@ -46,9 +46,9 @@ pub(crate) async fn add_file( Ok(()) } -/// delete_file +/// `delete_file` /// Interface: DELETE {path}/{type}/{name} -pub(crate) async fn delete_file( +pub async fn delete_file( path: P, auth: AuthFromRequest, ) -> ApiResult { @@ -74,9 +74,9 @@ pub(crate) async fn delete_file( Ok(()) } -/// get_file +/// `get_file` /// Interface: GET {path}/{type}/{name} -pub(crate) async fn get_file( +pub async fn get_file( path: P, auth: AuthFromRequest, range: Option>, @@ -124,13 +124,12 @@ pub(crate) async fn get_file( //============================================================================== /// Returns a stream for the given path in the repository. -pub(crate) async fn get_save_file( +pub async fn get_save_file( user: String, path: PathBuf, - tpe: impl Into>, + tpe: Option, name: Option, ) -> ApiResult { - let tpe = tpe.into(); tracing::debug!("[get_save_file] path: {path:?}, tpe: {tpe:?}, name: {name:?}"); let _ = check_name(tpe, name.as_deref())?; @@ -147,12 +146,12 @@ pub(crate) async fn get_save_file( } /// saves the content in the HTML request body to a file stream. -pub(crate) async fn save_body( - mut write_stream: impl AsyncWrite + Unpin + Finalizer, +pub async fn save_body( + mut write_stream: impl AsyncWrite + Unpin + Finalizer + Send, stream: S, ) -> ApiResult where - S: Stream>, + S: Stream> + Send, E: Into, { // Convert the stream into an `AsyncRead`. @@ -171,7 +170,7 @@ where } #[cfg(test)] -fn check_string_sha256(_name: &str) -> bool { +const fn check_string_sha256(_name: &str) -> bool { true } @@ -188,7 +187,7 @@ fn check_string_sha256(name: &str) -> bool { true } -pub(crate) fn check_name( +pub fn check_name( tpe: impl Into>, name: Option<&str>, ) -> ApiResult { diff --git a/src/handlers/file_helpers.rs b/src/handlers/file_helpers.rs index 69fb91d..9b1e06b 100644 --- a/src/handlers/file_helpers.rs +++ b/src/handlers/file_helpers.rs @@ -99,7 +99,7 @@ impl Drop for WriteOrDeleteFile { pub struct IteratorAdapter(RefCell); impl IteratorAdapter { - pub fn new(iterator: I) -> Self { + pub const fn new(iterator: I) -> Self { Self(RefCell::new(iterator)) } } diff --git a/src/handlers/file_length.rs b/src/handlers/file_length.rs index 12b7b68..67bca13 100644 --- a/src/handlers/file_length.rs +++ b/src/handlers/file_length.rs @@ -14,7 +14,7 @@ use crate::{ /// Length /// Interface: HEAD {path}/{type}/{name} -pub(crate) async fn file_length( +pub async fn file_length( path: P, auth: AuthFromRequest, ) -> ApiResult { diff --git a/src/handlers/files_list.rs b/src/handlers/files_list.rs index 23086a6..fd1b47a 100644 --- a/src/handlers/files_list.rs +++ b/src/handlers/files_list.rs @@ -27,10 +27,10 @@ enum ApiVersionKind { } impl ApiVersionKind { - pub fn to_static_str(&self) -> &'static str { + pub const fn to_static_str(self) -> &'static str { match self { - ApiVersionKind::V1 => "application/vnd.x.restic.rest.v1", - ApiVersionKind::V2 => "application/vnd.x.restic.rest.v2", + Self::V1 => "application/vnd.x.restic.rest.v1", + Self::V2 => "application/vnd.x.restic.rest.v2", } } } @@ -38,8 +38,8 @@ impl ApiVersionKind { impl std::fmt::Display for ApiVersionKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - ApiVersionKind::V1 => write!(f, "application/vnd.x.restic.rest.v1"), - ApiVersionKind::V2 => write!(f, "application/vnd.x.restic.rest.v2"), + Self::V1 => write!(f, "application/vnd.x.restic.rest.v1"), + Self::V2 => write!(f, "application/vnd.x.restic.rest.v2"), } } } @@ -49,8 +49,8 @@ impl FromStr for ApiVersionKind { fn from_str(s: &str) -> Result { match s { - "application/vnd.x.restic.rest.v1" => Ok(ApiVersionKind::V1), - "application/vnd.x.restic.rest.v2" => Ok(ApiVersionKind::V2), + "application/vnd.x.restic.rest.v1" => Ok(Self::V1), + "application/vnd.x.restic.rest.v2" => Ok(Self::V2), _ => Err(ApiErrorKind::InvalidApiVersion(s.to_string())), } } @@ -64,7 +64,7 @@ struct RepoPathEntry { size: u64, } -pub(crate) async fn list_files( +pub async fn list_files( path: P, auth: AuthFromRequest, headers: HeaderMap, diff --git a/src/handlers/repository.rs b/src/handlers/repository.rs index a3f6c87..b4ebeda 100644 --- a/src/handlers/repository.rs +++ b/src/handlers/repository.rs @@ -12,15 +12,15 @@ use crate::{ use crate::typed_path::PathParts; use strum::VariantNames; -/// Create_repository +/// `Create_repository` /// Interface: POST {path}?create=true #[derive(Default, Deserialize)] #[serde(default)] -pub(crate) struct Create { +pub struct Create { create: bool, } -pub(crate) async fn create_repository( +pub async fn create_repository( path: P, auth: AuthFromRequest, Query(params): Query, @@ -42,7 +42,7 @@ pub(crate) async fn create_repository( continue; } - storage.create_dir(&path, Some(tpe)).await? + storage.create_dir(&path, Some(tpe)).await?; } Ok(( @@ -57,10 +57,10 @@ pub(crate) async fn create_repository( } } -/// Delete_repository +/// `Delete_repository` /// Interface: Delete {path} // FIXME: The input path should at least NOT point to a file in any repository -pub(crate) async fn delete_repository( +pub async fn delete_repository( path: P, auth: AuthFromRequest, ) -> ApiResult { diff --git a/src/htpasswd.rs b/src/htpasswd.rs index b1fc6dd..c964e8e 100644 --- a/src/htpasswd.rs +++ b/src/htpasswd.rs @@ -50,7 +50,7 @@ impl Htpasswd { Self::default() } - pub fn from_file(pth: &PathBuf) -> AppResult { + pub fn from_file(pth: &PathBuf) -> AppResult { let mut c = CredentialMap::new(); if pth.exists() { @@ -70,7 +70,7 @@ impl Htpasswd { }); } - Ok(Htpasswd { + Ok(Self { path: pth.clone(), credentials: c, }) @@ -83,7 +83,7 @@ impl Htpasswd { pub fn create(&mut self, name: &str, pass: &str) -> AppResult<()> { let cred = Credential::new(name, pass); - let _ = self.insert(cred)?; + self.insert(cred)?; Ok(()) } @@ -165,14 +165,14 @@ impl Credential { let hash = md5_apr1_encode(pass, salt.as_str()); let hash = format_hash(hash.as_str(), salt.as_str()); - Credential { + Self { name: name.into(), hash, } } /// Returns a credential struct from a htpasswd file line - pub fn from_line(line: String) -> AppResult { + pub fn from_line(line: String) -> AppResult { let split: Vec<&str> = line.split(':').collect(); if split.len() != 2 { @@ -184,7 +184,7 @@ impl Credential { .into()); } - Ok(Credential { + Ok(Self { name: split[0].to_string(), hash: split[1].to_string(), }) diff --git a/src/lib.rs b/src/lib.rs index bba515b..aaedcdc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,4 @@ -//! RusticServer +//! `RusticServer` //! //! Application based on the [Abscissa] framework. //! @@ -64,7 +64,7 @@ pub mod typed_path; /// Web module /// /// implements a REST server as specified by -/// https://restic.readthedocs.io/en/stable/REST_backend.html?highlight=Rest%20API +/// pub mod web; #[cfg(test)] diff --git a/src/log.rs b/src/log.rs index 6f7976f..60c861c 100644 --- a/src/log.rs +++ b/src/log.rs @@ -60,7 +60,7 @@ pub async fn print_request_response( async fn buffer_and_print(uuid: &uuid::Uuid, body: B) -> Result where - B: axum::body::HttpBody, + B: axum::body::HttpBody + Send, B::Error: std::fmt::Display, { let bytes = match body.collect().await { diff --git a/src/prelude.rs b/src/prelude.rs index 8bf220e..c365790 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -1,6 +1,6 @@ //! Application-local prelude: conveniently import types/functions/macros //! which are generally useful and should be available in every module with -//! `use crate::prelude::*; +//! `use crate::prelude::*;` /// Abscissa core prelude pub use abscissa_core::prelude::*; diff --git a/src/storage.rs b/src/storage.rs index 2097eda..829d5d8 100644 --- a/src/storage.rs +++ b/src/storage.rs @@ -84,7 +84,7 @@ impl Storage for LocalStorage { ApiErrorKind::CreatingDirectoryFailed(format!( "Could not create directory: {err}" )) - })? + })?; } Ok(()) } @@ -107,11 +107,10 @@ impl Storage for LocalStorage { path: &Path, tpe: Option<&str>, ) -> Box> { - let path = if let Some(tpe) = tpe { - self.path.join(path).join(tpe) - } else { - self.path.join(path) - }; + let path = tpe.map_or_else( + || self.path.join(path), + |tpe| self.path.join(path).join(tpe), + ); let walker = WalkDir::new(path) .into_iter() @@ -204,6 +203,6 @@ mod test { // path must not start with slash !! that will skip the self.path from Storage! let path = PathBuf::new().join("test_repo/"); let c = storage.open_file(&path, "", Some("config")).await; - assert!(c.is_ok()) + assert!(c.is_ok()); } } diff --git a/src/test_helpers.rs b/src/test_helpers.rs index d2e4325..d05e802 100644 --- a/src/test_helpers.rs +++ b/src/test_helpers.rs @@ -42,7 +42,7 @@ pub(crate) fn init_tracing() { /// When we initialize the global tracing subscriber, this must only happen once. /// During tests, each test will initialize, to make sure we have at least tracing once. -/// This means that the init() call must be robust for this. +/// This means that the `init()` call must be robust for this. /// Since we do not need this in production code, it is located in the test code. static TRACER: OnceLock> = OnceLock::new(); fn init_mutex() { diff --git a/src/typed_path.rs b/src/typed_path.rs index 1e2dc99..e047ec7 100644 --- a/src/typed_path.rs +++ b/src/typed_path.rs @@ -2,7 +2,7 @@ use axum_extra::routing::TypedPath; use serde_derive::{Deserialize, Serialize}; use strum::{AsRefStr, Display, EnumString, IntoStaticStr, VariantNames}; -pub trait PathParts { +pub trait PathParts: Send { fn parts(&self) -> (Option, Option, Option) { (self.repo(), self.tpe(), self.name()) } diff --git a/tests/acceptance.rs b/tests/acceptance.rs index 89d2f39..1665c92 100644 --- a/tests/acceptance.rs +++ b/tests/acceptance.rs @@ -28,7 +28,7 @@ use std::io::Read; /// the runner acquire a mutex when executing commands and inspecting /// exit statuses, serializing what would otherwise be multithreaded /// invocations as `cargo test` executes tests in parallel by default. -pub static RUNNER: Lazy = Lazy::new(|| CmdRunner::default()); +pub static RUNNER: Lazy = Lazy::new(CmdRunner::default); // /// Use `RusticServerConfig::default()` value if no config or args // #[test]