Skip to content
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

style: simplify string formatting for readability #2442

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
2 changes: 1 addition & 1 deletion examples/nop-preprocessor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/book/book.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")?;
Expand Down Expand Up @@ -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)
Expand Down
22 changes: 8 additions & 14 deletions src/book/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down Expand Up @@ -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"
))
})?;

Expand All @@ -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"
))
})?;

Expand Down Expand Up @@ -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> {
Expand All @@ -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))
}
Expand Down Expand Up @@ -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}");
}
};

Expand Down
4 changes: 2 additions & 2 deletions src/book/summary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -616,7 +616,7 @@ impl Display for SectionNumber {
write!(f, "0")
} else {
for item in &self.0 {
write!(f, "{}.", item)?;
write!(f, "{item}.")?;
}
Ok(())
}
Expand Down Expand Up @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions src/cmd/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
24 changes: 12 additions & 12 deletions src/preprocess/links.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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 {
Expand All @@ -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 {
Expand All @@ -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 {
Expand All @@ -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 {
Expand All @@ -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 {
Expand All @@ -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 {
Expand All @@ -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 {
Expand All @@ -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,
Expand All @@ -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![
Expand Down Expand Up @@ -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],
Expand Down
22 changes: 6 additions & 16 deletions src/renderer/html_handlebars/hbs_renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand Down Expand Up @@ -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)?;
Expand Down Expand Up @@ -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}>"##
)
}

Expand All @@ -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()
}
Expand Down Expand Up @@ -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
}
Expand Down
6 changes: 3 additions & 3 deletions src/renderer/html_handlebars/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)?;
Expand Down Expand Up @@ -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)
};
Expand Down Expand Up @@ -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) => {}
}
Expand Down
Loading