Skip to content

Fix clippy warnings #2014

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

Closed
wants to merge 7 commits into from
Closed
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
4 changes: 2 additions & 2 deletions guide/src/for_developers/mdbook-wordcount/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ fn main() {
}

let num_words = count_words(ch);
println!("{}: {}", ch.name, num_words);
writeln!(f, "{}: {}", ch.name, num_words).unwrap();
println!("{}: {num_words}", ch.name);
writeln!(f, "{}: {num_words}", ch.name).unwrap();

if cfg.deny_odds && num_words % 2 == 1 {
eprintln!("{} has an odd number of words!", ch.name);
Expand Down
2 changes: 1 addition & 1 deletion guide/src/for_developers/preprocessors.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ fn remove_emphasis(
});

cmark(events, &mut buf, None).map(|_| buf).map_err(|err| {
Error::from(format!("Markdown serialization failed: {}", err))
Error::from(format!("Markdown serialization failed: {err}"))
})
}
```
Expand Down
10 changes: 5 additions & 5 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 @@ -277,7 +277,7 @@ fn load_chapter<P: AsRef<Path>>(
}

let stripped = location
.strip_prefix(&src_dir)
.strip_prefix(src_dir)
.expect("Chapters are always inside a book");

Chapter::new(&link.name, content, stripped, parent_names.clone())
Expand Down Expand Up @@ -317,7 +317,7 @@ impl<'a> Iterator for BookItems<'a> {
fn next(&mut self) -> Option<Self::Item> {
let item = self.items.pop_front();

if let Some(&BookItem::Chapter(ref ch)) = item {
if let Some(BookItem::Chapter(ch)) = item {
// if we wanted a breadth-first iterator we'd `extend()` here
for sub_item in ch.sub_items.iter().rev() {
self.items.push_front(sub_item);
Expand All @@ -331,7 +331,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
11 changes: 5 additions & 6 deletions src/book/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ impl BookBuilder {
match MDBook::load(&self.root) {
Ok(book) => Ok(book),
Err(e) => {
error!("{}", e);
error!("{e}");

panic!(
"The BookBuilder should always create a valid book. If you are seeing this it \
Expand Down Expand Up @@ -194,14 +194,13 @@ impl BookBuilder {
let summary = src_dir.join("SUMMARY.md");
if !summary.exists() {
trace!("No summary found creating stub summary and chapter_1.md.");
let mut f = File::create(&summary).with_context(|| "Unable to create SUMMARY.md")?;
let mut f = File::create(summary).with_context(|| "Unable to create SUMMARY.md")?;
writeln!(f, "# Summary")?;
writeln!(f)?;
writeln!(f, "- [Chapter 1](./chapter_1.md)")?;

let chapter_1 = src_dir.join("chapter_1.md");
let mut f =
File::create(&chapter_1).with_context(|| "Unable to create chapter_1.md")?;
let mut f = File::create(chapter_1).with_context(|| "Unable to create chapter_1.md")?;
writeln!(f, "# Chapter 1")?;
} else {
trace!("Existing summary found, no need to create stub files.");
Expand All @@ -214,10 +213,10 @@ impl BookBuilder {
fs::create_dir_all(&self.root)?;

let src = self.root.join(&self.config.book.src);
fs::create_dir_all(&src)?;
fs::create_dir_all(src)?;

let build = self.root.join(&self.config.build.build_dir);
fs::create_dir_all(&build)?;
fs::create_dir_all(build)?;

Ok(())
}
Expand Down
46 changes: 19 additions & 27 deletions src/book/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ impl MDBook {
}

if log_enabled!(log::Level::Trace) {
for line in format!("Config: {:#?}", config).lines() {
trace!("{}", line);
for line in format!("Config: {config:#?}").lines() {
trace!("{line}");
}
}

Expand All @@ -99,7 +99,7 @@ impl MDBook {
let root = book_root.into();

let src_dir = root.join(&config.book.src);
let book = book::load_book(&src_dir, &config.build)?;
let book = book::load_book(src_dir, &config.build)?;

let renderers = determine_renderers(&config);
let preprocessors = determine_preprocessors(&config)?;
Expand All @@ -122,7 +122,7 @@ impl MDBook {
let root = book_root.into();

let src_dir = root.join(&config.book.src);
let book = book::load_book_from_disk(&summary, &src_dir)?;
let book = book::load_book_from_disk(&summary, src_dir)?;

let renderers = determine_renderers(&config);
let preprocessors = determine_preprocessors(&config)?;
Expand Down Expand Up @@ -292,7 +292,7 @@ impl MDBook {
info!("Testing chapter '{}': {:?}", ch.name, chapter_path);

// write preprocessed file to tempdir
let path = temp_dir.path().join(&chapter_path);
let path = temp_dir.path().join(chapter_path);
let mut tmpf = utils::fs::create_file(&path)?;
tmpf.write_all(ch.content.as_bytes())?;

Expand All @@ -302,18 +302,18 @@ impl MDBook {
if let Some(edition) = self.config.rust.edition {
match edition {
RustEdition::E2015 => {
cmd.args(&["--edition", "2015"]);
cmd.args(["--edition", "2015"]);
}
RustEdition::E2018 => {
cmd.args(&["--edition", "2018"]);
cmd.args(["--edition", "2018"]);
}
RustEdition::E2021 => {
cmd.args(&["--edition", "2021"]);
cmd.args(["--edition", "2021"]);
}
}
}

debug!("running {:?}", cmd);
debug!("running {cmd:?}");
let output = cmd.output()?;

if !output.status.success() {
Expand All @@ -332,7 +332,7 @@ impl MDBook {
}
if let Some(chapter) = chapter {
if !chapter_found {
bail!("Chapter not found: {}", chapter);
bail!("Chapter not found: {chapter}");
}
}
Ok(())
Expand Down Expand Up @@ -441,24 +441,21 @@ 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",
))
})?;

if !exists(after) {
// Only warn so that preprocessors can be toggled on and off (e.g. for
// troubleshooting) without having to worry about order too much.
warn!(
"preprocessor.{}.after contains \"{}\", which was not found",
name, after
"preprocessor.{name}.after contains \"{after}\", which was not found",
);
} else {
preprocessor_names.add_dependency(name, after);
Expand All @@ -468,24 +465,19 @@ 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",
))
})?;

if !exists(before) {
// See equivalent warning above for rationale
warn!(
"preprocessor.{}.before contains \"{}\", which was not found",
name, before
"preprocessor.{name}.before contains \"{before}\", which was not found",
);
} else {
preprocessor_names.add_dependency(before, name);
Expand Down Expand Up @@ -539,7 +531,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 @@ -550,7 +542,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 @@ -744,7 +736,7 @@ mod tests {
for preprocessor in &preprocessors {
eprintln!(" {}", preprocessor.name());
}
panic!("{} should come before {}", before, after);
panic!("{before} should come before {after}");
}
};

Expand Down
26 changes: 10 additions & 16 deletions src/book/summary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ macro_rules! collect_events {

loop {
let event = $stream.next().map(|(ev, _range)| ev);
trace!("Next event: {:?}", event);
trace!("Next event: {event:?}");

match event {
Some($delimiter) => break,
Expand Down Expand Up @@ -394,7 +394,7 @@ impl<'a> SummaryParser<'a> {
items.extend(bunch_of_items);
}
Some(Event::Start(other_tag)) => {
trace!("Skipping contents of {:?}", other_tag);
trace!("Skipping contents of {other_tag:?}");

// Skip over the contents of this tag
while let Some(event) = self.next_event() {
Expand Down Expand Up @@ -426,7 +426,7 @@ impl<'a> SummaryParser<'a> {
/// Push an event back to the tail of the stream.
fn back(&mut self, ev: Event<'a>) {
assert!(self.back.is_none());
trace!("Back: {:?}", ev);
trace!("Back: {ev:?}");
self.back = Some(ev);
}

Expand All @@ -438,13 +438,13 @@ impl<'a> SummaryParser<'a> {
})
});

trace!("Next event: {:?}", next);
trace!("Next event: {next:?}");

next
}

fn parse_nested_numbered(&mut self, parent: &SectionNumber) -> Result<Vec<SummaryItem>> {
debug!("Parsing numbered chapters at level {}", parent);
debug!("Parsing numbered chapters at level {parent}");
let mut items = Vec::new();

loop {
Expand Down Expand Up @@ -492,8 +492,7 @@ impl<'a> SummaryParser<'a> {
let mut number = parent.clone();
number.0.push(num_existing_items as u32 + 1);
trace!(
"Found chapter: {} {} ({})",
number,
"Found chapter: {number} {} ({})",
link.name,
link.location
.as_ref()
Expand All @@ -506,7 +505,7 @@ impl<'a> SummaryParser<'a> {
return Ok(SummaryItem::Link(link));
}
other => {
warn!("Expected a start of a link, actually got {:?}", other);
warn!("Expected a start of a link, actually got {other:?}");
bail!(self.parse_error(
"The link items for nested chapters must only contain a hyperlink"
));
Expand All @@ -517,12 +516,7 @@ impl<'a> SummaryParser<'a> {

fn parse_error<D: Display>(&self, msg: D) -> Error {
let (line, col) = self.current_location();
anyhow::anyhow!(
"failed to parse SUMMARY.md line {}, column {}: {}",
line,
col,
msg
)
anyhow::anyhow!("failed to parse SUMMARY.md line {line}, column {col}: {msg}")
}

/// Try to parse the title line.
Expand Down Expand Up @@ -598,7 +592,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 @@ -745,7 +739,7 @@ mod tests {

let href = match parser.stream.next() {
Some((Event::Start(Tag::Link(_type, href, _title)), _range)) => href.to_string(),
other => panic!("Unreachable, {:?}", other),
other => panic!("Unreachable, {other:?}"),
};

let got = parser.parse_link(href);
Expand Down
2 changes: 1 addition & 1 deletion src/cmd/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub fn make_subcommand() -> Command {
// Build command implementation
pub fn execute(args: &ArgMatches) -> Result<()> {
let book_dir = get_book_dir(args);
let mut book = MDBook::load(&book_dir)?;
let mut book = MDBook::load(book_dir)?;

if let Some(dest_dir) = args.get_one::<PathBuf>("dest-dir") {
book.config.build.build_dir = dest_dir.into();
Expand Down
2 changes: 1 addition & 1 deletion src/cmd/clean.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub fn make_subcommand() -> Command {
// Clean command implementation
pub fn execute(args: &ArgMatches) -> mdbook::errors::Result<()> {
let book_dir = get_book_dir(args);
let book = MDBook::load(&book_dir)?;
let book = MDBook::load(book_dir)?;

let dir_to_remove = match args.get_one::<PathBuf>("dest-dir") {
Some(dest_dir) => dest_dir.into(),
Expand Down
6 changes: 3 additions & 3 deletions src/cmd/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ pub fn execute(args: &ArgMatches) -> Result<()> {
};

if let Some(author) = get_author_name() {
debug!("Obtained user name from gitconfig: {:?}", author);
debug!("Obtained user name from gitconfig: {author:?}");
config.book.authors.push(author);
builder.with_config(config);
}
Expand All @@ -84,7 +84,7 @@ pub fn execute(args: &ArgMatches) -> Result<()> {
/// Obtains author name from git config file by running the `git config` command.
fn get_author_name() -> Option<String> {
let output = Command::new("git")
.args(&["config", "--get", "user.name"])
.args(["config", "--get", "user.name"])
.output()
.ok()?;

Expand Down Expand Up @@ -114,5 +114,5 @@ fn confirm() -> bool {
io::stdout().flush().unwrap();
let mut s = String::new();
io::stdin().read_line(&mut s).ok();
matches!(&*s.trim(), "Y" | "y" | "yes" | "Yes")
matches!(s.trim(), "Y" | "y" | "yes" | "Yes")
}
Loading