use inline string formatting

This commit is contained in:
neri 2022-10-07 15:52:12 +02:00
parent d7b6d31198
commit 171bfc98a9
6 changed files with 22 additions and 28 deletions

View File

@ -30,18 +30,15 @@ fn get_db_url() -> String {
let auth = if let Ok(user) = env::var("DATABASE_USER") { let auth = if let Ok(user) = env::var("DATABASE_USER") {
if let Ok(pass) = env::var("DATABASE_PASS") { if let Ok(pass) = env::var("DATABASE_PASS") {
format!("{}:{}@", user, pass) format!("{user}:{pass}@")
} else { } else {
format!("{}@", user) format!("{user}@")
} }
} else { } else {
String::new() String::new()
}; };
format!( let host = env::var("DATABASE_HOST").unwrap_or_else(|_| "localhost".to_string());
"postgresql://{auth}{host}/{name}", let name = env::var("DATABASE_NAME").unwrap_or_else(|_| "datatrash".to_string());
auth = auth, format!("postgresql://{auth}{host}/{name}")
host = env::var("DATABASE_HOST").unwrap_or_else(|_| "localhost".to_string()),
name = env::var("DATABASE_NAME").unwrap_or_else(|_| "datatrash".to_string())
)
} }

View File

@ -16,7 +16,7 @@ fn load_mime_aliases() -> HashMap<Mime, Mime> {
tree_magic_db::aliases() tree_magic_db::aliases()
.lines() .lines()
.flat_map(|line| line.split_once(' ')) .flat_map(|line| line.split_once(' '))
.flat_map(|(a, b)| Some((Mime::from_str(a).ok()?, Mime::from_str(b).ok()?))) .flat_map(|(alias, mime)| Some((Mime::from_str(alias).ok()?, Mime::from_str(mime).ok()?)))
.collect() .collect()
} }

View File

@ -47,7 +47,7 @@ pub(crate) async fn parse_multipart(
content_type = Some(if mime == APPLICATION_OCTET_STREAM { content_type = Some(if mime == APPLICATION_OCTET_STREAM {
get_content_type(file_path) get_content_type(file_path)
} else { } else {
mime.clone() mime_relations::get_alias(mime)
}); });
} }
"text" => { "text" => {
@ -69,11 +69,10 @@ pub(crate) async fn parse_multipart(
let content_type = let content_type =
content_type.ok_or_else(|| error::ErrorBadRequest("no content type found"))?; content_type.ok_or_else(|| error::ErrorBadRequest("no content type found"))?;
let content_type = mime_relations::get_alias(content_type);
let keep_for = keep_for_seconds let keep_for = keep_for_seconds
.map(|k| k.parse()) .map(|k| k.parse())
.transpose() .transpose()
.map_err(|e| error::ErrorBadRequest(format!("field keep_for is not a number: {}", e)))? .map_err(|e| error::ErrorBadRequest(format!("field keep_for is not a number: {e}")))?
.map(Duration::seconds) .map(Duration::seconds)
.unwrap_or(DEFAULT_UPLOAD_DURATION); .unwrap_or(DEFAULT_UPLOAD_DURATION);
let valid_till = OffsetDateTime::now_utc() + keep_for; let valid_till = OffsetDateTime::now_utc() + keep_for;
@ -105,8 +104,7 @@ fn check_requirements(
if *keep_for > MAX_UPLOAD_DURATION { if *keep_for > MAX_UPLOAD_DURATION {
return Err(error::ErrorBadRequest(format!( return Err(error::ErrorBadRequest(format!(
"maximum allowed validity is {}, but you specified {}", "maximum allowed validity is {MAX_UPLOAD_DURATION}, but you specified {keep_for}"
MAX_UPLOAD_DURATION, keep_for
))); )));
} }
@ -136,7 +134,7 @@ fn get_field_name(field: &Field) -> Result<String, error::Error> {
async fn parse_string(name: &str, field: actix_multipart::Field) -> Result<String, error::Error> { async fn parse_string(name: &str, field: actix_multipart::Field) -> Result<String, error::Error> {
let data = read_content(field).await?; let data = read_content(field).await?;
String::from_utf8(data) String::from_utf8(data)
.map_err(|_| error::ErrorBadRequest(format!("could not parse field {} as utf-8", name))) .map_err(|_| error::ErrorBadRequest(format!("could not parse field {name} as utf-8")))
} }
async fn read_content(mut field: actix_multipart::Field) -> Result<Vec<u8>, error::Error> { async fn read_content(mut field: actix_multipart::Field) -> Result<Vec<u8>, error::Error> {
@ -172,8 +170,7 @@ async fn write_to_file(
if let Some(max_size) = max_size { if let Some(max_size) = max_size {
if written_bytes > max_size { if written_bytes > max_size {
return Err(error::ErrorBadRequest(format!( return Err(error::ErrorBadRequest(format!(
"exceeded maximum file size of {} bytes", "exceeded maximum file size of {max_size} bytes"
max_size
))); )));
} }
} }

View File

@ -34,7 +34,7 @@ impl KeyExtractor for ForwardedPeerIpKeyExtractor {
.wait_time_from(DefaultClock::default().now()) .wait_time_from(DefaultClock::default().now())
.as_secs(); .as_secs();
( (
format!("too many requests, retry in {}s", wait_time), format!("too many requests, retry in {wait_time}s"),
ContentType::plaintext(), ContentType::plaintext(),
) )
} }

View File

@ -61,7 +61,7 @@ fn render_file_size(size: u64) -> String {
let magnitude = cmp::min((size as f64).log(1024.0) as u32, 5); let magnitude = cmp::min((size as f64).log(1024.0) as u32, 5);
let prefix = ["", "ki", "Mi", "Gi", "Ti", "Pi"][magnitude as usize]; let prefix = ["", "ki", "Mi", "Gi", "Ti", "Pi"][magnitude as usize];
let value = size / (1024_u64.pow(magnitude)); let value = size / (1024_u64.pow(magnitude));
format!("{}{}B", value, prefix) format!("{value}{prefix}B")
} }
fn render_duration(duration: Duration) -> String { fn render_duration(duration: Duration) -> String {
@ -88,8 +88,8 @@ fn render_duration(duration: Duration) -> String {
fn pluralize(number: i64, word: &str, suffix: &str) -> Option<String> { fn pluralize(number: i64, word: &str, suffix: &str) -> Option<String> {
match number { match number {
0 => None, 0 => None,
1 => Some(format!("{} {}", number, word)), 1 => Some(format!("{number} {word}")),
_ => Some(format!("{} {}{}", number, word, suffix)), _ => Some(format!("{number} {word}{suffix}")),
} }
} }

View File

@ -66,8 +66,7 @@ pub async fn upload(
let file_name = original_name.clone().unwrap_or_else(|| { let file_name = original_name.clone().unwrap_or_else(|| {
format!( format!(
"{}.{}", "{file_id}.{}",
file_id,
mime_relations::get_extension(&content_type).unwrap_or("txt") mime_relations::get_extension(&content_type).unwrap_or("txt")
) )
}); });
@ -108,15 +107,15 @@ pub async fn upload(
let redirect = if let Some(original_name) = original_name.as_ref() { let redirect = if let Some(original_name) = original_name.as_ref() {
let encoded_name = urlencoding::encode(original_name); let encoded_name = urlencoding::encode(original_name);
format!("/upload/{}/{}", file_id, encoded_name) format!("/upload/{file_id}/{encoded_name}")
} else { } else {
format!("/upload/{}", file_id) format!("/upload/{file_id}")
}; };
let url = get_file_url(&req, &file_id, original_name.as_deref()); let url = get_file_url(&req, &file_id, original_name.as_deref());
Ok(HttpResponse::SeeOther() Ok(HttpResponse::SeeOther()
.insert_header((LOCATION, redirect)) .insert_header((LOCATION, redirect))
.body(format!("{}\n", url))) .body(format!("{url}\n")))
} }
async fn create_unique_file( async fn create_unique_file(
@ -149,11 +148,12 @@ fn gen_file_id() -> String {
} }
fn get_file_url(req: &HttpRequest, id: &str, name: Option<&str>) -> String { fn get_file_url(req: &HttpRequest, id: &str, name: Option<&str>) -> String {
let host = template::get_host_url(req);
if let Some(name) = name { if let Some(name) = name {
let encoded_name = urlencoding::encode(name); let encoded_name = urlencoding::encode(name);
format!("{}/{}/{}", template::get_host_url(req), id, encoded_name) format!("{host}/{id}/{encoded_name}")
} else { } else {
format!("{}/{}", template::get_host_url(req), id) format!("{host}/{id}")
} }
} }