Skip to content

Use format arguments capture feature #4440

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

Merged
merged 1 commit into from
Jan 13, 2022
Merged
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
21 changes: 7 additions & 14 deletions cargo-registry-markdown/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -390,62 +390,55 @@ mod tests {
assert_eq!(
result,
format!(
"<p><a href=\"https://{}/rust-lang/test/blob/HEAD/hi\" rel=\"nofollow noopener noreferrer\">hi</a></p>\n",
host
"<p><a href=\"https://{host}/rust-lang/test/blob/HEAD/hi\" rel=\"nofollow noopener noreferrer\">hi</a></p>\n"
)
);

let result = markdown_to_html(relative, Some(&url), "");
assert_eq!(
result,
format!(
"<p><a href=\"https://{}/rust-lang/test/blob/HEAD/there\" rel=\"nofollow noopener noreferrer\">there</a></p>\n",
host
"<p><a href=\"https://{host}/rust-lang/test/blob/HEAD/there\" rel=\"nofollow noopener noreferrer\">there</a></p>\n"
)
);

let result = markdown_to_html(image, Some(&url), "");
assert_eq!(
result,
format!(
"<p><img src=\"https://{}/rust-lang/test/raw/HEAD/img.png\" alt=\"alt\"></p>\n",
host
"<p><img src=\"https://{host}/rust-lang/test/raw/HEAD/img.png\" alt=\"alt\"></p>\n",
)
);

let result = markdown_to_html(html_image, Some(&url), "");
assert_eq!(
result,
format!(
"<img src=\"https://{}/rust-lang/test/raw/HEAD/img.png\" alt=\"alt\">\n",
host
"<img src=\"https://{host}/rust-lang/test/raw/HEAD/img.png\" alt=\"alt\">\n",
)
);

let result = markdown_to_html(svg, Some(&url), "");
assert_eq!(
result,
format!(
"<p><img src=\"https://{}/rust-lang/test/raw/HEAD/sanitize.svg?sanitize=true\" alt=\"alt\"></p>\n",
host
"<p><img src=\"https://{host}/rust-lang/test/raw/HEAD/sanitize.svg?sanitize=true\" alt=\"alt\"></p>\n",
)
);

let result = markdown_to_html(svg, Some(&url), "subdir");
assert_eq!(
result,
format!(
"<p><img src=\"https://{}/rust-lang/test/raw/HEAD/subdir/sanitize.svg?sanitize=true\" alt=\"alt\"></p>\n",
host
"<p><img src=\"https://{host}/rust-lang/test/raw/HEAD/subdir/sanitize.svg?sanitize=true\" alt=\"alt\"></p>\n",
)
);

let result = markdown_to_html(svg, Some(&url), "subdir1/subdir2");
assert_eq!(
result,
format!(
"<p><img src=\"https://{}/rust-lang/test/raw/HEAD/subdir1/subdir2/sanitize.svg?sanitize=true\" alt=\"alt\"></p>\n",
host
"<p><img src=\"https://{host}/rust-lang/test/raw/HEAD/subdir1/subdir2/sanitize.svg?sanitize=true\" alt=\"alt\"></p>\n",
)
);
}
Expand Down
6 changes: 1 addition & 5 deletions cargo-registry-s3/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ impl Bucket {
"{}.s3{}.amazonaws.com",
self.name,
match self.region {
Some(ref r) if !r.is_empty() => format!("-{}", r),
Some(ref r) if !r.is_empty() => format!("-{r}"),
Some(_) => String::new(),
None => String::new(),
}
Expand All @@ -95,13 +95,9 @@ impl Bucket {
fn auth(&self, verb: &str, date: &str, path: &str, md5: &str, content_type: &str) -> String {
let string = format!(
"{verb}\n{md5}\n{ty}\n{date}\n{headers}/{name}/{path}",
verb = verb,
md5 = md5,
ty = content_type,
date = date,
headers = "",
name = self.name,
path = path
);
let signature = {
let key = self.secret_key.as_bytes();
Expand Down
2 changes: 1 addition & 1 deletion src/admin/delete_crate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ fn delete(opts: Opts, conn: &PgConnection) {
let n = diesel::delete(crates::table.find(krate.id))
.execute(conn)
.unwrap();
println!(" {} deleted", n);
println!(" {n} deleted");

if !dialoguer::confirm("commit?") {
panic!("aborting transaction");
Expand Down
2 changes: 1 addition & 1 deletion src/admin/on_call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl Event {
let response = Client::new()
.post("https://events.pagerduty.com/generic/2010-04-15/create_event.json")
.header(header::ACCEPT, "application/vnd.pagerduty+json;version=2")
.header(header::AUTHORIZATION, format!("Token token={}", api_token))
.header(header::AUTHORIZATION, format!("Token token={api_token}"))
.json(&FullEvent {
service_key,
event: self,
Expand Down
20 changes: 10 additions & 10 deletions src/admin/render_readmes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ pub fn run(opts: Opts) -> anyhow::Result<()> {
};
let older_than = older_than.naive_utc();

println!("Start time: {}", start_time);
println!("Rendering readmes older than: {}", older_than);
println!("Start time: {start_time}");
println!("Rendering readmes older than: {older_than}");

let mut query = versions::table
.inner_join(crates::table)
Expand All @@ -67,14 +67,14 @@ pub fn run(opts: Opts) -> anyhow::Result<()> {
.into_boxed();

if let Some(crate_name) = opts.crate_name {
println!("Rendering readmes for {}", crate_name);
println!("Rendering readmes for {crate_name}");
query = query.filter(crates::name.eq(crate_name));
}

let version_ids: Vec<i32> = query.load(&conn).expect("error loading version ids");

let total_versions = version_ids.len();
println!("Rendering {} versions", total_versions);
println!("Rendering {total_versions} versions");

let page_size = opts.page_size;

Expand Down Expand Up @@ -138,8 +138,8 @@ pub fn run(opts: Opts) -> anyhow::Result<()> {
}
for handle in tasks {
match handle.join() {
Err(err) => println!("Thread panicked: {:?}", err),
Ok(Err(err)) => println!("Thread failed: {:?}", err),
Err(err) => println!("Thread panicked: {err:?}"),
Ok(Err(err)) => println!("Thread failed: {err:?}"),
_ => {}
}
}
Expand All @@ -161,7 +161,7 @@ fn get_readme(

let location = match uploader {
Uploader::S3 { .. } => location,
Uploader::Local => format!("http://localhost:8888/{}", location),
Uploader::Local => format!("http://localhost:8888/{location}"),
};

let mut extra_headers = header::HeaderMap::new();
Expand All @@ -188,7 +188,7 @@ fn render_pkg_readme<R: Read>(mut archive: Archive<R>, pkg_name: &str) -> anyhow
let mut entries = archive.entries().context("Invalid tar archive entries")?;

let manifest: Manifest = {
let path = format!("{}/Cargo.toml", pkg_name);
let path = format!("{pkg_name}/Cargo.toml");
let contents = find_file_by_path(&mut entries, Path::new(&path))
.context("Failed to read Cargo.toml file")?;

Expand All @@ -201,9 +201,9 @@ fn render_pkg_readme<R: Read>(mut archive: Archive<R>, pkg_name: &str) -> anyhow
.readme
.clone()
.unwrap_or_else(|| "README.md".into());
let path = format!("{}/{}", pkg_name, readme_path);
let path = format!("{pkg_name}/{readme_path}");
let contents = find_file_by_path(&mut entries, Path::new(&path))
.with_context(|| format!("Failed to read {} file", readme_path))?;
.with_context(|| format!("Failed to read {readme_path} file"))?;

// pkg_path_in_vcs Unsupported from admin::render_readmes. See #4095
// Would need access to cargo_vcs_info
Expand Down
2 changes: 1 addition & 1 deletion src/bin/enqueue-job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ fn main() -> Result<()> {
let mut args = std::env::args().skip(1);

let job = args.next().unwrap_or_default();
println!("Enqueueing background job: {}", job);
println!("Enqueueing background job: {job}");

match &*job {
"update_downloads" => {
Expand Down
13 changes: 6 additions & 7 deletions src/bin/monitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,7 @@ fn check_failing_background_jobs(conn: &PgConnection) -> Result<()> {
on_call::Event::Trigger {
incident_key: Some(EVENT_KEY.into()),
description: format!(
"{} jobs have been in the queue for more than {} minutes",
stalled_job_count, max_job_time
"{stalled_job_count} jobs have been in the queue for more than {max_job_time} minutes"
),
}
} else {
Expand Down Expand Up @@ -95,7 +94,7 @@ fn check_stalled_update_downloads(conn: &PgConnection) -> Result<()> {
if minutes > max_job_time {
return log_and_trigger_event(on_call::Event::Trigger {
incident_key: Some(EVENT_KEY.into()),
description: format!("update_downloads job running for {} minutes", minutes),
description: format!("update_downloads job running for {minutes} minutes"),
});
}
};
Expand Down Expand Up @@ -130,13 +129,13 @@ fn check_spam_attack(conn: &PgConnection) -> Result<()> {
.optional()?;

if let Some(bad_crate) = bad_crate {
event_description = Some(format!("Crate named {} published", bad_crate));
event_description = Some(format!("Crate named {bad_crate} published"));
}

let event = if let Some(event_description) = event_description {
on_call::Event::Trigger {
incident_key: Some(EVENT_KEY.into()),
description: format!("{}, possible spam attack underway", event_description,),
description: format!("{event_description}, possible spam attack underway"),
}
} else {
on_call::Event::Resolve {
Expand All @@ -153,11 +152,11 @@ fn log_and_trigger_event(event: on_call::Event) -> Result<()> {
match event {
on_call::Event::Trigger {
ref description, ..
} => println!("Paging on-call: {}", description),
} => println!("Paging on-call: {description}"),
on_call::Event::Resolve {
description: Some(ref description),
..
} => println!("{}", description),
} => println!("{description}"),
_ => {} // noop
}
event.send()
Expand Down
10 changes: 5 additions & 5 deletions src/bin/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {

// Do not change this line! Removing the line or changing its contents in any way will break
// the test suite :)
println!("Listening at http://{}", addr);
println!("Listening at http://{addr}");

// Creating this file tells heroku to tell nginx that the application is ready
// to receive traffic.
Expand All @@ -120,7 +120,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
} else {
"/tmp/app-initialized"
};
println!("Writing to {}", path);
println!("Writing to {path}");
File::create(path).unwrap();

// Launch nginx via the Heroku nginx buildpack
Expand All @@ -137,7 +137,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Persisting remaining downloads counters");
match app.downloads_counter.persist_all_shards(&app) {
Ok(stats) => stats.log(),
Err(err) => println!("downloads_counter error: {}", err),
Err(err) => println!("downloads_counter error: {err}"),
}

println!("Server has gracefully shutdown!");
Expand All @@ -154,7 +154,7 @@ fn downloads_counter_thread(app: Arc<App>) {

match app.downloads_counter.persist_next_shard(&app) {
Ok(stats) => stats.log(),
Err(err) => println!("downloads_counter error: {}", err),
Err(err) => println!("downloads_counter error: {err}"),
}
});
}
Expand All @@ -169,7 +169,7 @@ fn log_instance_metrics_thread(app: Arc<App>) {

std::thread::spawn(move || loop {
if let Err(err) = log_instance_metrics_inner(&app) {
eprintln!("log_instance_metrics error: {}", err);
eprintln!("log_instance_metrics error: {err}");
}
std::thread::sleep(interval);
});
Expand Down
6 changes: 3 additions & 3 deletions src/boot/categories.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ impl Category {
fn required_string_from_toml<'a>(toml: &'a toml::value::Table, key: &str) -> Result<&'a str> {
toml.get(key)
.and_then(toml::Value::as_str)
.with_context(|| format!("Expected category TOML attribute '{}' to be a String", key))
.with_context(|| format!("Expected category TOML attribute '{key}' to be a String"))
}

fn optional_string_from_toml<'a>(toml: &'a toml::value::Table, key: &str) -> &'a str {
Expand All @@ -54,7 +54,7 @@ fn categories_from_toml(
for (slug, details) in categories {
let details = details
.as_table()
.with_context(|| format!("category {} was not a TOML table", slug))?;
.with_context(|| format!("category {slug} was not a TOML table"))?;

let category = Category::from_parent(
slug,
Expand All @@ -66,7 +66,7 @@ fn categories_from_toml(
if let Some(categories) = details.get("categories") {
let categories = categories
.as_table()
.with_context(|| format!("child categories of {} were not a table", slug))?;
.with_context(|| format!("child categories of {slug} were not a table"))?;

result.extend(categories_from_toml(categories, Some(&category))?);
}
Expand Down
2 changes: 1 addition & 1 deletion src/controllers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ mod prelude {
let query_string = url::form_urlencoded::Serializer::new(String::new())
.extend_pairs(params)
.finish();
format!("?{}", query_string)
format!("?{query_string}")
}

fn log_metadata<V: std::fmt::Display>(&mut self, key: &'static str, value: V) {
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/krate/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ pub fn search(req: &mut dyn RequestExt) -> EndpointResult {
.filter(
categories::slug
.eq(cat)
.or(categories::slug.like(format!("{}::%", cat))),
.or(categories::slug.like(format!("{cat}::%"))),
),
),
);
Expand Down
6 changes: 3 additions & 3 deletions src/controllers/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ pub fn new(req: &mut dyn RequestExt) -> EndpointResult {
.ok_or_else(|| bad_request("missing header: Content-Length"))?;

if length > max_size {
return Err(bad_request(&format!("max content length is: {}", max_size)));
return Err(bad_request(&format!("max content length is: {max_size}")));
}

let mut json = vec![0; length as usize];
Expand All @@ -52,7 +52,7 @@ pub fn new(req: &mut dyn RequestExt) -> EndpointResult {
String::from_utf8(json).map_err(|_| bad_request(&"json body was not valid utf-8"))?;

let new: NewApiTokenRequest = json::from_str(&json)
.map_err(|e| bad_request(&format!("invalid new token request: {:?}", e)))?;
.map_err(|e| bad_request(&format!("invalid new token request: {e:?}")))?;

let name = &new.api_token.name;
if name.is_empty() {
Expand Down Expand Up @@ -88,7 +88,7 @@ pub fn new(req: &mut dyn RequestExt) -> EndpointResult {
pub fn revoke(req: &mut dyn RequestExt) -> EndpointResult {
let id = req.params()["id"]
.parse::<i32>()
.map_err(|e| bad_request(&format!("invalid token id: {:?}", e)))?;
.map_err(|e| bad_request(&format!("invalid token id: {e:?}")))?;

let authenticated_user = req.authenticate()?;
let conn = req.db_conn()?;
Expand Down
6 changes: 2 additions & 4 deletions src/controllers/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,8 @@ fn verify_origin(req: &dyn RequestExt) -> AppResult<()> {
.find(|value| !allowed_origins.iter().any(|it| it == value));

if let Some(bad_origin) = bad_origin {
let error_message = format!(
"only same-origin requests can be authenticated. got {:?}",
bad_origin
);
let error_message =
format!("only same-origin requests can be authenticated. got {bad_origin:?}");
return Err(internal(&error_message).chain(forbidden()));
}
Ok(())
Expand Down
7 changes: 2 additions & 5 deletions src/email.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,9 @@ https://{}/confirm/{}",
) -> AppResult<()> {
let subject = "Crate ownership invitation";
let body = format!(
"{} has invited you to become an owner of the crate {}!\n
Visit https://{domain}/accept-invite/{} to accept this invitation,
"{user_name} has invited you to become an owner of the crate {crate_name}!\n
Visit https://{domain}/accept-invite/{token} to accept this invitation,
or go to https://{domain}/me/pending-invites to manage all of your crate ownership invitations.",
user_name,
crate_name,
token,
domain = crate::config::domain_name()
);

Expand Down
Loading