From 1fd9656291c8e42ebdc3cdeba3db91f8daf8293e Mon Sep 17 00:00:00 2001 From: Hamir Mahal Date: Sat, 21 Sep 2024 15:53:59 -0700 Subject: [PATCH 1/2] style: simplify string formatting for readability --- examples/nop-preprocessor.rs | 2 +- src/book/book.rs | 6 ++--- src/book/mod.rs | 20 +++++++--------- src/book/summary.rs | 4 ++-- src/cmd/serve.rs | 4 ++-- src/config.rs | 2 +- src/preprocess/links.rs | 24 ++++++++++---------- src/renderer/html_handlebars/hbs_renderer.rs | 19 +++++----------- src/renderer/html_handlebars/search.rs | 6 ++--- src/utils/fs.rs | 24 ++++++++++---------- src/utils/mod.rs | 6 ++--- tests/alternative_backends.rs | 4 ++-- tests/init.rs | 10 ++++---- 13 files changed, 59 insertions(+), 72 deletions(-) diff --git a/examples/nop-preprocessor.rs b/examples/nop-preprocessor.rs index 398d7fc7..ee561e95 100644 --- a/examples/nop-preprocessor.rs +++ b/examples/nop-preprocessor.rs @@ -26,7 +26,7 @@ fn main() { if let Some(sub_args) = matches.subcommand_matches("supports") { handle_supports(&preprocessor, sub_args); } else if let Err(e) = handle_preprocessing(&preprocessor) { - eprintln!("{}", e); + eprintln!("{e}"); process::exit(1); } } diff --git a/src/book/book.rs b/src/book/book.rs index f08350c2..5bb4480e 100644 --- a/src/book/book.rs +++ b/src/book/book.rs @@ -18,11 +18,11 @@ pub fn load_book>(src_dir: P, cfg: &BuildConfig) -> Result let mut summary_content = String::new(); File::open(&summary_md) - .with_context(|| format!("Couldn't open SUMMARY.md in {:?} directory", src_dir))? + .with_context(|| format!("Couldn't open SUMMARY.md in {src_dir:?} directory"))? .read_to_string(&mut summary_content)?; let summary = parse_summary(&summary_content) - .with_context(|| format!("Summary parsing failed for file={:?}", summary_md))?; + .with_context(|| format!("Summary parsing failed for file={summary_md:?}"))?; if cfg.create_missing { create_missing(src_dir, &summary).with_context(|| "Unable to create missing chapters")?; @@ -341,7 +341,7 @@ impl<'a> Iterator for BookItems<'a> { impl Display for Chapter { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { if let Some(ref section_number) = self.number { - write!(f, "{} ", section_number)?; + write!(f, "{section_number} ")?; } write!(f, "{}", self.name) diff --git a/src/book/mod.rs b/src/book/mod.rs index 92990ea8..dfd803c6 100644 --- a/src/book/mod.rs +++ b/src/book/mod.rs @@ -92,7 +92,7 @@ impl MDBook { } if log_enabled!(log::Level::Trace) { - for line in format!("Config: {:#?}", config).lines() { + for line in format!("Config: {config:#?}").lines() { trace!("{}", line); } } @@ -483,15 +483,13 @@ fn determine_preprocessors(config: &Config) -> Result> if let Some(before) = table.get("before") { let before = before.as_array().ok_or_else(|| { Error::msg(format!( - "Expected preprocessor.{}.before to be an array", - name + "Expected preprocessor.{name}.before to be an array" )) })?; for after in before { let after = after.as_str().ok_or_else(|| { Error::msg(format!( - "Expected preprocessor.{}.before to contain strings", - name + "Expected preprocessor.{name}.before to contain strings" )) })?; @@ -511,15 +509,13 @@ fn determine_preprocessors(config: &Config) -> Result> if let Some(after) = table.get("after") { let after = after.as_array().ok_or_else(|| { Error::msg(format!( - "Expected preprocessor.{}.after to be an array", - name + "Expected preprocessor.{name}.after to be an array" )) })?; for before in after { let before = before.as_str().ok_or_else(|| { Error::msg(format!( - "Expected preprocessor.{}.after to contain strings", - name + "Expected preprocessor.{name}.after to contain strings" )) })?; @@ -581,7 +577,7 @@ fn get_custom_preprocessor_cmd(key: &str, table: &Value) -> String { .get("command") .and_then(Value::as_str) .map(ToString::to_string) - .unwrap_or_else(|| format!("mdbook-{}", key)) + .unwrap_or_else(|| format!("mdbook-{key}")) } fn interpret_custom_renderer(key: &str, table: &Value) -> Box { @@ -592,7 +588,7 @@ fn interpret_custom_renderer(key: &str, table: &Value) -> Box { .and_then(Value::as_str) .map(ToString::to_string); - let command = table_dot_command.unwrap_or_else(|| format!("mdbook-{}", key)); + let command = table_dot_command.unwrap_or_else(|| format!("mdbook-{key}")); Box::new(CmdRenderer::new(key.to_string(), command)) } @@ -786,7 +782,7 @@ mod tests { for preprocessor in &preprocessors { eprintln!(" {}", preprocessor.name()); } - panic!("{} should come before {}", before, after); + panic!("{before} should come before {after}"); } }; diff --git a/src/book/summary.rs b/src/book/summary.rs index 6c71e54e..30006f22 100644 --- a/src/book/summary.rs +++ b/src/book/summary.rs @@ -616,7 +616,7 @@ impl Display for SectionNumber { write!(f, "0") } else { for item in &self.0 { - write!(f, "{}.", item)?; + write!(f, "{item}.")?; } Ok(()) } @@ -763,7 +763,7 @@ mod tests { let href = match parser.stream.next() { Some((Event::Start(Tag::Link { dest_url, .. }), _range)) => dest_url.to_string(), - other => panic!("Unreachable, {:?}", other), + other => panic!("Unreachable, {other:?}"), }; let got = parser.parse_link(href); diff --git a/src/cmd/serve.rs b/src/cmd/serve.rs index 5e637a02..7b1ccab6 100644 --- a/src/cmd/serve.rs +++ b/src/cmd/serve.rs @@ -54,7 +54,7 @@ pub fn execute(args: &ArgMatches) -> Result<()> { let hostname = args.get_one::("hostname").unwrap(); let open_browser = args.get_flag("open"); - let address = format!("{}:{}", hostname, port); + let address = format!("{hostname}:{port}"); let update_config = |book: &mut MDBook| { book.config @@ -89,7 +89,7 @@ pub fn execute(args: &ArgMatches) -> Result<()> { serve(build_dir, sockaddr, reload_tx, &file_404); }); - let serving_url = format!("http://{}", address); + let serving_url = format!("http://{address}"); info!("Serving on: {}", serving_url); if open_browser { diff --git a/src/config.rs b/src/config.rs index 1438be29..b87ad276 100644 --- a/src/config.rs +++ b/src/config.rs @@ -145,7 +145,7 @@ impl Config { if let serde_json::Value::Object(ref map) = parsed_value { // To `set` each `key`, we wrap them as `prefix.key` for (k, v) in map { - let full_key = format!("{}.{}", key, k); + let full_key = format!("{key}.{k}"); self.set(&full_key, v).expect("unreachable"); } return; diff --git a/src/preprocess/links.rs b/src/preprocess/links.rs index 0af21196..99d9b9ea 100644 --- a/src/preprocess/links.rs +++ b/src/preprocess/links.rs @@ -493,7 +493,7 @@ mod tests { let s = "Some random text with {{#playground file.rs}} and {{#playground test.rs }}..."; let res = find_links(s).collect::>(); - println!("\nOUTPUT: {:?}\n", res); + println!("\nOUTPUT: {res:?}\n"); assert_eq!( res, @@ -519,7 +519,7 @@ mod tests { let s = "Some random text with {{#playground foo-bar\\baz/_c++.rs}}..."; let res = find_links(s).collect::>(); - println!("\nOUTPUT: {:?}\n", res); + println!("\nOUTPUT: {res:?}\n"); assert_eq!( res, @@ -536,7 +536,7 @@ mod tests { fn test_find_links_with_range() { let s = "Some random text with {{#include file.rs:10:20}}..."; let res = find_links(s).collect::>(); - println!("\nOUTPUT: {:?}\n", res); + println!("\nOUTPUT: {res:?}\n"); assert_eq!( res, vec![Link { @@ -555,7 +555,7 @@ mod tests { fn test_find_links_with_line_number() { let s = "Some random text with {{#include file.rs:10}}..."; let res = find_links(s).collect::>(); - println!("\nOUTPUT: {:?}\n", res); + println!("\nOUTPUT: {res:?}\n"); assert_eq!( res, vec![Link { @@ -574,7 +574,7 @@ mod tests { fn test_find_links_with_from_range() { let s = "Some random text with {{#include file.rs:10:}}..."; let res = find_links(s).collect::>(); - println!("\nOUTPUT: {:?}\n", res); + println!("\nOUTPUT: {res:?}\n"); assert_eq!( res, vec![Link { @@ -593,7 +593,7 @@ mod tests { fn test_find_links_with_to_range() { let s = "Some random text with {{#include file.rs::20}}..."; let res = find_links(s).collect::>(); - println!("\nOUTPUT: {:?}\n", res); + println!("\nOUTPUT: {res:?}\n"); assert_eq!( res, vec![Link { @@ -612,7 +612,7 @@ mod tests { fn test_find_links_with_full_range() { let s = "Some random text with {{#include file.rs::}}..."; let res = find_links(s).collect::>(); - println!("\nOUTPUT: {:?}\n", res); + println!("\nOUTPUT: {res:?}\n"); assert_eq!( res, vec![Link { @@ -631,7 +631,7 @@ mod tests { fn test_find_links_with_no_range_specified() { let s = "Some random text with {{#include file.rs}}..."; let res = find_links(s).collect::>(); - println!("\nOUTPUT: {:?}\n", res); + println!("\nOUTPUT: {res:?}\n"); assert_eq!( res, vec![Link { @@ -650,7 +650,7 @@ mod tests { fn test_find_links_with_anchor() { let s = "Some random text with {{#include file.rs:anchor}}..."; let res = find_links(s).collect::>(); - println!("\nOUTPUT: {:?}\n", res); + println!("\nOUTPUT: {res:?}\n"); assert_eq!( res, vec![Link { @@ -670,7 +670,7 @@ mod tests { let s = "Some random text with escaped playground \\{{#playground file.rs editable}} ..."; let res = find_links(s).collect::>(); - println!("\nOUTPUT: {:?}\n", res); + println!("\nOUTPUT: {res:?}\n"); assert_eq!( res, @@ -690,7 +690,7 @@ mod tests { more\n text {{#playground my.rs editable no_run should_panic}} ..."; let res = find_links(s).collect::>(); - println!("\nOUTPUT: {:?}\n", res); + println!("\nOUTPUT: {res:?}\n"); assert_eq!( res, vec![ @@ -721,7 +721,7 @@ mod tests { no_run should_panic}} ..."; let res = find_links(s).collect::>(); - println!("\nOUTPUT: {:?}\n", res); + println!("\nOUTPUT: {res:?}\n"); assert_eq!(res.len(), 3); assert_eq!( res[0], diff --git a/src/renderer/html_handlebars/hbs_renderer.rs b/src/renderer/html_handlebars/hbs_renderer.rs index 080b12da..4dd2b934 100644 --- a/src/renderer/html_handlebars/hbs_renderer.rs +++ b/src/renderer/html_handlebars/hbs_renderer.rs @@ -153,13 +153,13 @@ impl HtmlHandlebars { let content_404 = if let Some(ref filename) = html_config.input_404 { let path = src_dir.join(filename); std::fs::read_to_string(&path) - .with_context(|| format!("unable to open 404 input file {:?}", path))? + .with_context(|| format!("unable to open 404 input file {path:?}"))? } else { // 404 input not explicitly configured try the default file 404.md let default_404_location = src_dir.join("404.md"); if default_404_location.exists() { std::fs::read_to_string(&default_404_location).with_context(|| { - format!("unable to open 404 input file {:?}", default_404_location) + format!("unable to open 404 input file {default_404_location:?}") })? } else { "# Document not found (404)\n\nThis URL is invalid, sorry. Please use the \ @@ -237,7 +237,7 @@ impl HtmlHandlebars { )?; if let Some(cname) = &html_config.cname { - write_file(destination, "CNAME", format!("{}\n", cname).as_bytes())?; + write_file(destination, "CNAME", format!("{cname}\n").as_bytes())?; } write_file(destination, "book.js", &theme.js)?; @@ -834,11 +834,7 @@ fn insert_link_into_header( .unwrap_or_default(); format!( - r##"{text}"##, - level = level, - id = id, - text = content, - classes = classes + r##"{content}"## ) } @@ -861,10 +857,7 @@ fn fix_code_blocks(html: &str) -> String { let after = &caps[3]; format!( - r#""#, - before = before, - classes = classes, - after = after + r#""# ) }) .into_owned() @@ -923,7 +916,7 @@ fn add_playground_pre( // we need to inject our own main let (attrs, code) = partition_source(code); - format!("# #![allow(unused)]\n{}#fn main() {{\n{}#}}", attrs, code) + format!("# #![allow(unused)]\n{attrs}#fn main() {{\n{code}#}}") .into() }; content diff --git a/src/renderer/html_handlebars/search.rs b/src/renderer/html_handlebars/search.rs index 1144c9f5..c03eb4f8 100644 --- a/src/renderer/html_handlebars/search.rs +++ b/src/renderer/html_handlebars/search.rs @@ -50,7 +50,7 @@ pub fn create_files(search_config: &Search, destination: &Path, book: &Book) -> utils::fs::write_file( destination, "searchindex.js", - format!("Object.assign(window.search, {});", index).as_bytes(), + format!("Object.assign(window.search, {index});").as_bytes(), )?; utils::fs::write_file(destination, "searcher.js", searcher::JS)?; utils::fs::write_file(destination, "mark.min.js", searcher::MARK_JS)?; @@ -83,7 +83,7 @@ fn add_doc( }); let url = if let Some(id) = section_id { - Cow::Owned(format!("{}#{}", anchor_base, id)) + Cow::Owned(format!("{anchor_base}#{id}")) } else { Cow::Borrowed(anchor_base) }; @@ -203,7 +203,7 @@ fn render_item( Event::FootnoteReference(name) => { let len = footnote_numbers.len() + 1; let number = footnote_numbers.entry(name).or_insert(len); - body.push_str(&format!(" [{}] ", number)); + body.push_str(&format!(" [{number}] ")); } Event::TaskListMarker(_checked) => {} } diff --git a/src/utils/fs.rs b/src/utils/fs.rs index 0a441321..220bcd8b 100644 --- a/src/utils/fs.rs +++ b/src/utils/fs.rs @@ -228,47 +228,47 @@ mod tests { fn copy_files_except_ext_test() { let tmp = match tempfile::TempDir::new() { Ok(t) => t, - Err(e) => panic!("Could not create a temp dir: {}", e), + Err(e) => panic!("Could not create a temp dir: {e}"), }; // Create a couple of files if let Err(err) = fs::File::create(tmp.path().join("file.txt")) { - panic!("Could not create file.txt: {}", err); + panic!("Could not create file.txt: {err}"); } if let Err(err) = fs::File::create(tmp.path().join("file.md")) { - panic!("Could not create file.md: {}", err); + panic!("Could not create file.md: {err}"); } if let Err(err) = fs::File::create(tmp.path().join("file.png")) { - panic!("Could not create file.png: {}", err); + panic!("Could not create file.png: {err}"); } if let Err(err) = fs::create_dir(tmp.path().join("sub_dir")) { - panic!("Could not create sub_dir: {}", err); + panic!("Could not create sub_dir: {err}"); } if let Err(err) = fs::File::create(tmp.path().join("sub_dir/file.png")) { - panic!("Could not create sub_dir/file.png: {}", err); + panic!("Could not create sub_dir/file.png: {err}"); } if let Err(err) = fs::create_dir(tmp.path().join("sub_dir_exists")) { - panic!("Could not create sub_dir_exists: {}", err); + panic!("Could not create sub_dir_exists: {err}"); } if let Err(err) = fs::File::create(tmp.path().join("sub_dir_exists/file.txt")) { - panic!("Could not create sub_dir_exists/file.txt: {}", err); + panic!("Could not create sub_dir_exists/file.txt: {err}"); } if let Err(err) = symlink(tmp.path().join("file.png"), tmp.path().join("symlink.png")) { - panic!("Could not symlink file.png: {}", err); + panic!("Could not symlink file.png: {err}"); } // Create output dir if let Err(err) = fs::create_dir(tmp.path().join("output")) { - panic!("Could not create output: {}", err); + panic!("Could not create output: {err}"); } if let Err(err) = fs::create_dir(tmp.path().join("output/sub_dir_exists")) { - panic!("Could not create output/sub_dir_exists: {}", err); + panic!("Could not create output/sub_dir_exists: {err}"); } if let Err(e) = copy_files_except_ext(tmp.path(), &tmp.path().join("output"), true, None, &["md"]) { - panic!("Error while executing the function:\n{:?}", e); + panic!("Error while executing the function:\n{e:?}"); } // Check if the correct files where created diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 2b17cc7d..ab6d93e8 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -77,7 +77,7 @@ pub fn unique_id_from_content(content: &str, id_counter: &mut HashMap id, - id_count => format!("{}-{}", id, id_count), + id_count => format!("{id}-{id_count}"), }; *id_count += 1; unique_id @@ -105,7 +105,7 @@ fn adjust_links<'a>(event: Event<'a>, path: Option<&Path>) -> Event<'a> { if base.ends_with(".md") { base.replace_range(base.len() - 3.., ".html"); } - return format!("{}{}", base, dest).into(); + return format!("{base}{dest}").into(); } else { return dest; } @@ -121,7 +121,7 @@ fn adjust_links<'a>(event: Event<'a>, path: Option<&Path>) -> Event<'a> { .to_str() .expect("utf-8 paths only"); if !base.is_empty() { - write!(fixed_link, "{}/", base).unwrap(); + write!(fixed_link, "{base}/").unwrap(); } } diff --git a/tests/alternative_backends.rs b/tests/alternative_backends.rs index 7ef654c9..d5f1f0f4 100644 --- a/tests/alternative_backends.rs +++ b/tests/alternative_backends.rs @@ -117,12 +117,12 @@ fn dummy_book_with_backend( let mut config = Config::default(); config - .set(format!("output.{}.command", name), command) + .set(format!("output.{name}.command"), command) .unwrap(); if backend_is_optional { config - .set(format!("output.{}.optional", name), true) + .set(format!("output.{name}.optional"), true) .unwrap(); } diff --git a/tests/init.rs b/tests/init.rs index 2b6ad507..e952ed19 100644 --- a/tests/init.rs +++ b/tests/init.rs @@ -23,7 +23,7 @@ fn base_mdbook_init_should_create_default_content() { for file in &created_files { let target = temp.path().join(file); println!("{}", target.display()); - assert!(target.exists(), "{} doesn't exist", file); + assert!(target.exists(), "{file} doesn't exist"); } let contents = fs::read_to_string(temp.path().join("book.toml")).unwrap(); @@ -59,7 +59,7 @@ fn run_mdbook_init_should_create_content_from_summary() { for file in &created_files { let target = src_dir.join(file); println!("{}", target.display()); - assert!(target.exists(), "{} doesn't exist", file); + assert!(target.exists(), "{file} doesn't exist"); } } @@ -73,8 +73,7 @@ fn run_mdbook_init_with_custom_book_and_src_locations() { for file in &created_files { assert!( !temp.path().join(file).exists(), - "{} shouldn't exist yet!", - file + "{file} shouldn't exist yet!" ); } @@ -88,8 +87,7 @@ fn run_mdbook_init_with_custom_book_and_src_locations() { let target = temp.path().join(file); assert!( target.exists(), - "{} should have been created by `mdbook init`", - file + "{file} should have been created by `mdbook init`" ); } From f9add3e936787cdd7e6146fbd7315c8a73cc142f Mon Sep 17 00:00:00 2001 From: Hamir Mahal Date: Sat, 21 Sep 2024 15:56:13 -0700 Subject: [PATCH 2/2] fix: formatting in `src/` and `tests/` directories --- src/book/mod.rs | 4 +--- src/renderer/html_handlebars/hbs_renderer.rs | 7 ++----- tests/alternative_backends.rs | 4 +--- 3 files changed, 4 insertions(+), 11 deletions(-) diff --git a/src/book/mod.rs b/src/book/mod.rs index dfd803c6..608ed166 100644 --- a/src/book/mod.rs +++ b/src/book/mod.rs @@ -508,9 +508,7 @@ fn determine_preprocessors(config: &Config) -> Result> if let Some(after) = table.get("after") { let after = after.as_array().ok_or_else(|| { - Error::msg(format!( - "Expected preprocessor.{name}.after to be an array" - )) + Error::msg(format!("Expected preprocessor.{name}.after to be an array")) })?; for before in after { let before = before.as_str().ok_or_else(|| { diff --git a/src/renderer/html_handlebars/hbs_renderer.rs b/src/renderer/html_handlebars/hbs_renderer.rs index 4dd2b934..88214077 100644 --- a/src/renderer/html_handlebars/hbs_renderer.rs +++ b/src/renderer/html_handlebars/hbs_renderer.rs @@ -856,9 +856,7 @@ fn fix_code_blocks(html: &str) -> String { let classes = &caps[2].replace(',', " "); let after = &caps[3]; - format!( - r#""# - ) + format!(r#""#) }) .into_owned() } @@ -916,8 +914,7 @@ fn add_playground_pre( // we need to inject our own main let (attrs, code) = partition_source(code); - format!("# #![allow(unused)]\n{attrs}#fn main() {{\n{code}#}}") - .into() + format!("# #![allow(unused)]\n{attrs}#fn main() {{\n{code}#}}").into() }; content } diff --git a/tests/alternative_backends.rs b/tests/alternative_backends.rs index d5f1f0f4..8ed92439 100644 --- a/tests/alternative_backends.rs +++ b/tests/alternative_backends.rs @@ -121,9 +121,7 @@ fn dummy_book_with_backend( .unwrap(); if backend_is_optional { - config - .set(format!("output.{name}.optional"), true) - .unwrap(); + config.set(format!("output.{name}.optional"), true).unwrap(); } let md = MDBook::init(temp.path())