Merge pull request #2442 from hamirmahal/style/simplify-string-formatting-for-readability

style: simplify string formatting for readability
This commit is contained in:
Eric Huss 2024-09-25 20:49:56 +00:00 committed by GitHub
commit f4805343f8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 59 additions and 79 deletions

View file

@ -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);
}
}

View file

@ -18,11 +18,11 @@ pub fn load_book<P: AsRef<Path>>(src_dir: P, cfg: &BuildConfig) -> Result<Book>
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)

View file

@ -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<Vec<Box<dyn Preprocessor>>
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"
))
})?;
@ -510,16 +508,12 @@ fn determine_preprocessors(config: &Config) -> Result<Vec<Box<dyn Preprocessor>>
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
))
Error::msg(format!("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 +575,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<CmdRenderer> {
@ -592,7 +586,7 @@ fn interpret_custom_renderer(key: &str, table: &Value) -> Box<CmdRenderer> {
.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 +780,7 @@ mod tests {
for preprocessor in &preprocessors {
eprintln!(" {}", preprocessor.name());
}
panic!("{} should come before {}", before, after);
panic!("{before} should come before {after}");
}
};

View file

@ -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);

View file

@ -54,7 +54,7 @@ pub fn execute(args: &ArgMatches) -> Result<()> {
let hostname = args.get_one::<String>("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 {

View file

@ -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;

View file

@ -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::<Vec<_>>();
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::<Vec<_>>();
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::<Vec<_>>();
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::<Vec<_>>();
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::<Vec<_>>();
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::<Vec<_>>();
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::<Vec<_>>();
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::<Vec<_>>();
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::<Vec<_>>();
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::<Vec<_>>();
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::<Vec<_>>();
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::<Vec<_>>();
println!("\nOUTPUT: {:?}\n", res);
println!("\nOUTPUT: {res:?}\n");
assert_eq!(res.len(), 3);
assert_eq!(
res[0],

View file

@ -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##"<h{level} id="{id}"{classes}><a class="header" href="#{id}">{text}</a></h{level}>"##,
level = level,
id = id,
text = content,
classes = classes
r##"<h{level} id="{id}"{classes}><a class="header" href="#{id}">{content}</a></h{level}>"##
)
}
@ -860,12 +856,7 @@ fn fix_code_blocks(html: &str) -> String {
let classes = &caps[2].replace(',', " ");
let after = &caps[3];
format!(
r#"<code{before}class="{classes}"{after}>"#,
before = before,
classes = classes,
after = after
)
format!(r#"<code{before}class="{classes}"{after}>"#)
})
.into_owned()
}
@ -923,8 +914,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)
.into()
format!("# #![allow(unused)]\n{attrs}#fn main() {{\n{code}#}}").into()
};
content
}

View file

@ -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) => {}
}

View file

@ -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

View file

@ -77,7 +77,7 @@ pub fn unique_id_from_content(content: &str, id_counter: &mut HashMap<String, us
let id_count = id_counter.entry(id.clone()).or_insert(0);
let unique_id = match *id_count {
0 => 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();
}
}

View file

@ -117,13 +117,11 @@ 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)
.unwrap();
config.set(format!("output.{name}.optional"), true).unwrap();
}
let md = MDBook::init(temp.path())

View file

@ -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`"
);
}