Skip to content

Commit

Permalink
Fix clippy warnings (dandavison#1298)
Browse files Browse the repository at this point in the history
* Fix clippy warnings

- `clippy::uninlined_format_args`

* Fix clippy warnings

- `clippy::clone_on_copy`
- `clippy::explicit_auto_deref`
- `clippy::iter_cloned_collect`
- `clippy::map_clone`
- `clippy::needless_borrow`
- `clippy::needless_lifetimes`
- `clippy::needless_return`
- `clippy::redundant_clone`
- `clippy::redundant_field_names`
- `clippy::seek_to_start_instead_of_rewind`
- `clippy::unnecessary_cast`
- `clippy::unused_unit`
  • Loading branch information
nickelc committed Feb 28, 2023
1 parent ce6448f commit 28bf556
Show file tree
Hide file tree
Showing 42 changed files with 151 additions and 188 deletions.
2 changes: 1 addition & 1 deletion src/align.rs
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ mod tests {
}

impl<'a> TestCase<'a> {
pub fn run(&self) -> () {
pub fn run(&self) {
self.assert_string_distance_parts();
assert_eq!(operations(self.before, self.after), self.operations);
}
Expand Down
6 changes: 3 additions & 3 deletions src/ansi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub fn measure_text_width(s: &str) -> usize {
//
// 3. If tail was exhausted, then contribute graphemes and ANSI escape sequences from `s` until the
// display_width of the result would exceed `display_width`.
pub fn truncate_str<'a, 'b>(s: &'a str, display_width: usize, tail: &'b str) -> Cow<'a, str> {
pub fn truncate_str<'a>(s: &'a str, display_width: usize, tail: &str) -> Cow<'a, str> {
let items = ansi_strings_iterator(s).collect::<Vec<(&str, bool)>>();
let width = strip_ansi_codes_from_strings_iterator(items.iter().copied()).width();
if width <= display_width {
Expand Down Expand Up @@ -68,7 +68,7 @@ pub fn truncate_str<'a, 'b>(s: &'a str, display_width: usize, tail: &'b str) ->
}
}

Cow::from(format!("{}{}", result, result_tail))
Cow::from(format!("{result}{result_tail}"))
}

pub fn parse_style_sections(s: &str) -> Vec<(ansi_term::Style, &str)> {
Expand Down Expand Up @@ -176,7 +176,7 @@ pub fn explain_ansi(line: &str, colorful: bool) -> String {
if colorful {
format!("({}){}", style.to_painted_string(), style.paint(s))
} else {
format!("({}){}", style, s)
format!("({style}){s}")
}
})
.collect()
Expand Down
8 changes: 4 additions & 4 deletions src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub fn parse_color(s: &str, true_color: bool, git_config: Option<&GitConfig>) ->
return None;
}
let die = || {
fatal(format!("Invalid color or style attribute: {}", s));
fatal(format!("Invalid color or style attribute: {s}"));
};
let syntect_color = if s.starts_with('#') {
SyntectColor::from_str(s).unwrap_or_else(|_| die())
Expand All @@ -27,7 +27,7 @@ pub fn parse_color(s: &str, true_color: bool, git_config: Option<&GitConfig>) ->
.or_else(|| utils::syntect::syntect_color_from_name(s));
if syntect_color.is_none() {
if let Some(git_config) = git_config {
if let Some(val) = git_config.get::<String>(&format!("delta.{}", s)) {
if let Some(val) = git_config.get::<String>(&format!("delta.{s}")) {
return parse_color(&val, true_color, None);
}
}
Expand All @@ -41,8 +41,8 @@ pub fn parse_color(s: &str, true_color: bool, git_config: Option<&GitConfig>) ->
pub fn color_to_string(color: Color) -> String {
match color {
Color::Fixed(n) if n < 16 => ansi_16_color_number_to_name(n).unwrap().to_string(),
Color::Fixed(n) => format!("{}", n),
Color::RGB(r, g, b) => format!("\"#{:02x?}{:02x?}{:02x?}\"", r, g, b),
Color::Fixed(n) => format!("{n}"),
Color::RGB(r, g, b) => format!("\"#{r:02x?}{g:02x?}{b:02x?}\""),
Color::Black => "black".to_string(),
Color::Red => "red".to_string(),
Color::Green => "green".to_string(),
Expand Down
3 changes: 1 addition & 2 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -390,9 +390,8 @@ pub fn user_supplied_option(option: &str, arg_matches: &clap::ArgMatches) -> boo

pub fn delta_unreachable(message: &str) -> ! {
fatal(format!(
"{} This should not be possible. \
"{message} This should not be possible. \
Please report the bug at https://github.com/dandavison/delta/issues.",
message
));
}

Expand Down
4 changes: 2 additions & 2 deletions src/edits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -470,7 +470,7 @@ mod tests {
}

fn assert_tokenize(text: &str, expected_tokens: &[&str]) {
let actual_tokens = tokenize(text, &*DEFAULT_TOKENIZATION_REGEXP);
let actual_tokens = tokenize(text, &DEFAULT_TOKENIZATION_REGEXP);
assert_eq!(text, expected_tokens.iter().join(""));
// tokenize() guarantees that the first element of the token stream is "".
// See comment in Alignment::new()
Expand Down Expand Up @@ -861,7 +861,7 @@ mod tests {
Deletion,
noop_insertions,
Insertion,
&*DEFAULT_TOKENIZATION_REGEXP,
&DEFAULT_TOKENIZATION_REGEXP,
max_line_distance,
0.0,
);
Expand Down
16 changes: 7 additions & 9 deletions src/features/hyperlinks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub fn format_commit_line_with_osc8_commit_hyperlink<'a>(
let suffix = captures.get(3).map(|m| m.as_str()).unwrap_or("");
let formatted_commit =
format_osc8_hyperlink(&commit_link_format.replace("{commit}", commit), commit);
format!("{}{}{}", prefix, formatted_commit, suffix)
format!("{prefix}{formatted_commit}{suffix}")
})
} else if let Some(GitConfigEntry::GitRemote(repo)) =
config.git_config.as_ref().and_then(get_remote_url)
Expand Down Expand Up @@ -74,7 +74,7 @@ where
.hyperlinks_file_link_format
.replace("{path}", &absolute_path.as_ref().to_string_lossy());
if let Some(n) = line_number {
url = url.replace("{line}", &format!("{}", n))
url = url.replace("{line}", &format!("{n}"))
} else {
url = url.replace("{line}", "")
};
Expand Down Expand Up @@ -138,8 +138,7 @@ pub mod tests {
] {
run_test(FilePathsTestCase {
name: &format!(
"delta relative_paths={} calling_cmd={:?}",
delta_relative_paths_option, calling_cmd
"delta relative_paths={delta_relative_paths_option} calling_cmd={calling_cmd:?}",
),
true_location_of_file_relative_to_repo_root:
true_location_of_file_relative_to_repo_root.as_path(),
Expand Down Expand Up @@ -452,7 +451,7 @@ __path__: some matching line

fn run_test(test_case: FilePathsTestCase) {
let mut config = integration_test_utils::make_config_from_args(
&test_case
test_case
.get_args()
.iter()
.map(|s| s.as_str())
Expand Down Expand Up @@ -483,12 +482,11 @@ __path__: some matching line
test_case.path_in_delta_input,
test_case.path_in_grep_output()
);
delta_test.with_input(
&GIT_GREP_OUTPUT.replace("__path__", &test_case.path_in_delta_input),
)
delta_test
.with_input(&GIT_GREP_OUTPUT.replace("__path__", test_case.path_in_delta_input))
}
CallingProcess::OtherGrep => delta_test
.with_input(&GIT_GREP_OUTPUT.replace("__path__", &test_case.path_in_delta_input)),
.with_input(&GIT_GREP_OUTPUT.replace("__path__", test_case.path_in_delta_input)),
};
let make_expected_hyperlink = |text| {
format_osc8_hyperlink(
Expand Down
21 changes: 9 additions & 12 deletions src/features/line_numbers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ impl<'a> LineNumbersData<'a> {
format_data: if insert_center_space_on_odd_width {
let format_left = vec![format::FormatStringPlaceholderData::default()];
let format_right = vec![format::FormatStringPlaceholderData {
prefix: format!("{}", ODD_PAD_CHAR).into(),
prefix: format!("{ODD_PAD_CHAR}").into(),
prefix_len: 1,
..Default::default()
}];
Expand Down Expand Up @@ -327,9 +327,9 @@ pub mod tests {

use super::*;

pub fn parse_line_number_format_with_default_regex<'a>(
format_string: &'a str,
) -> FormatStringData<'a> {
pub fn parse_line_number_format_with_default_regex(
format_string: &str,
) -> FormatStringData<'_> {
format::parse_line_number_format(format_string, &LINE_NUMBERS_PLACEHOLDER_REGEX, false)
}

Expand Down Expand Up @@ -460,7 +460,7 @@ pub mod tests {
assert_eq!(
format::parse_line_number_format("|{nm:<4}|", &LINE_NUMBERS_PLACEHOLDER_REGEX, true),
vec![format::FormatStringPlaceholderData {
prefix: format!("{}|", ODD_PAD_CHAR).into(),
prefix: format!("{ODD_PAD_CHAR}|").into(),
placeholder: Some(Placeholder::NumberMinus),
alignment_spec: Some(Align::Left),
width: Some(4),
Expand All @@ -483,7 +483,7 @@ pub mod tests {
),
vec![
format::FormatStringPlaceholderData {
prefix: format!("{}|", ODD_PAD_CHAR).into(),
prefix: format!("{ODD_PAD_CHAR}|").into(),
placeholder: Some(Placeholder::NumberMinus),
alignment_spec: Some(Align::Left),
width: Some(4),
Expand Down Expand Up @@ -512,7 +512,7 @@ pub mod tests {
assert_eq!(
format::parse_line_number_format("|++|", &LINE_NUMBERS_PLACEHOLDER_REGEX, true),
vec![format::FormatStringPlaceholderData {
prefix: format!("{}", ODD_PAD_CHAR).into(),
prefix: format!("{ODD_PAD_CHAR}").into(),
placeholder: None,
alignment_spec: None,
width: None,
Expand All @@ -530,10 +530,7 @@ pub mod tests {
let long = "line number format which is too large for SSO";
assert!(long.len() > std::mem::size_of::<smol_str::SmolStr>());
assert_eq!(
parse_line_number_format_with_default_regex(&format!(
"{long}{{nm}}{long}",
long = long
),),
parse_line_number_format_with_default_regex(&format!("{long}{{nm}}{long}")),
vec![format::FormatStringPlaceholderData {
prefix: long.into(),
prefix_len: long.len(),
Expand Down Expand Up @@ -615,7 +612,7 @@ pub mod tests {
assert_eq!(data.formatted_width(), MinusPlus::new(32, 0));

let format = MinusPlus::new("│{np:^3}│ │{nm:<12}│ │{np}│".into(), "".into());
let mut data = LineNumbersData::from_format_strings(&format, w.clone());
let mut data = LineNumbersData::from_format_strings(&format, w);

data.initialize_hunk(&[(10, 11), (10000, 100001)], "a".into());
assert_eq!(data.formatted_width(), MinusPlus::new(32, 0));
Expand Down
2 changes: 1 addition & 1 deletion src/features/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ pub mod tests {
fn test_builtin_features_have_flags_and_these_set_features() {
let builtin_features = make_builtin_features();
let mut args = vec!["delta".to_string()];
args.extend(builtin_features.keys().map(|s| format!("--{}", s)));
args.extend(builtin_features.keys().map(|s| format!("--{s}")));
let opt = cli::Opt::from_iter_and_git_config(DeltaEnv::default(), args, None);
let features: HashSet<&str> = opt
.features
Expand Down
2 changes: 1 addition & 1 deletion src/features/navigate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ pub fn copy_less_hist_file_and_append_navigate_regex(config: &Config) -> std::io
initial_contents
};
if !contents.ends_with(".search\n") {
contents = format!("{}.search\n", contents);
contents = format!("{contents}.search\n");
}
writeln!(
std::fs::File::create(&delta_less_hist_file)?,
Expand Down
8 changes: 4 additions & 4 deletions src/features/side_by_side.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,10 +348,10 @@ fn paint_right_panel_plus_line<'a>(
}

#[allow(clippy::too_many_arguments)]
fn get_right_fill_style_for_panel<'a>(
fn get_right_fill_style_for_panel(
line_is_empty: bool,
line_index: Option<usize>,
diff_style_sections: &[LineSections<'a, Style>],
diff_style_sections: &[LineSections<'_, Style>],
lines_have_homolog: Option<&[bool]>,
state: &State,
panel_side: PanelSide,
Expand Down Expand Up @@ -468,11 +468,11 @@ fn paint_minus_or_plus_panel_line<'a>(
/// done with spaces. The right panel can be filled with spaces or using ANSI sequences
/// instructing the terminal emulator to fill the background color rightwards.
#[allow(clippy::too_many_arguments, clippy::comparison_chain)]
fn pad_panel_line_to_width<'a>(
fn pad_panel_line_to_width(
panel_line: &mut String,
panel_line_is_empty: bool,
line_index: Option<usize>,
diff_style_sections: &[LineSections<'a, Style>],
diff_style_sections: &[LineSections<'_, Style>],
lines_have_homolog: Option<&[bool]>,
state: &State,
panel_side: PanelSide,
Expand Down
16 changes: 9 additions & 7 deletions src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ pub enum Align {
impl TryFrom<Option<&str>> for Align {
type Error = ();
fn try_from(from: Option<&str>) -> Result<Self, Self::Error> {
// inlined format args are not supported for `debug_assert` with edition 2018.
#[allow(clippy::uninlined_format_args)]
match from {
Some(alignment) if alignment == "<" => Ok(Align::Left),
Some(alignment) if alignment == ">" => Ok(Align::Right),
Expand Down Expand Up @@ -162,7 +164,7 @@ pub fn parse_line_number_format<'a>(
let mut expand_first_prefix = |prefix: SmolStr| {
// Only prefix the first placeholder with a space, also see `UseFullPanelWidth`
if prefix_with_space {
let prefix = SmolStr::new(format!("{}{}", ODD_PAD_CHAR, prefix));
let prefix = SmolStr::new(format!("{ODD_PAD_CHAR}{prefix}"));
prefix_with_space = false;
prefix
} else {
Expand Down Expand Up @@ -300,14 +302,14 @@ pub fn pad<T: std::fmt::Display + CenterRightNumbers>(
let space = s.center_right_space(alignment, width);
let mut result = match precision {
None => match alignment {
Align::Left => format!("{0}{1:<2$}", space, s, width),
Align::Center => format!("{0}{1:^2$}", space, s, width),
Align::Right => format!("{0}{1:>2$}", space, s, width),
Align::Left => format!("{space}{s:<width$}"),
Align::Center => format!("{space}{s:^width$}"),
Align::Right => format!("{space}{s:>width$}"),
},
Some(precision) => match alignment {
Align::Left => format!("{0}{1:<2$.3$}", space, s, width, precision),
Align::Center => format!("{0}{1:^2$.3$}", space, s, width, precision),
Align::Right => format!("{0}{1:>2$.3$}", space, s, width, precision),
Align::Left => format!("{space}{s:<width$.precision$}"),
Align::Center => format!("{space}{s:^width$.precision$}"),
Align::Right => format!("{space}{s:>width$.precision$}"),
},
};
if space == " " {
Expand Down
19 changes: 8 additions & 11 deletions src/git_config/git_config_entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,16 @@ impl GitRemoteRepo {
pub fn format_commit_url(&self, commit: &str) -> String {
match self {
Self::GitHub { slug } => {
format!("https://github.com/{}/commit/{}", slug, commit)
format!("https://github.com/{slug}/commit/{commit}")
}
Self::GitLab { slug } => {
format!("https://gitlab.com/{}/-/commit/{}", slug, commit)
format!("https://gitlab.com/{slug}/-/commit/{commit}")
}
Self::SourceHut { slug } => {
format!("https://git.sr.ht/{}/commit/{}", slug, commit)
format!("https://git.sr.ht/{slug}/commit/{commit}")
}
Self::Codeberg { slug } => {
format!("https://codeberg.org/{}/commit/{}", slug, commit)
format!("https://codeberg.org/{slug}/commit/{commit}")
}
}
}
Expand Down Expand Up @@ -174,7 +174,7 @@ mod tests {
let commit_hash = "d3b07384d113edec49eaa6238ad5ff00";
assert_eq!(
repo.format_commit_url(commit_hash),
format!("https://github.com/dandavison/delta/commit/{}", commit_hash)
format!("https://github.com/dandavison/delta/commit/{commit_hash}")
)
}

Expand Down Expand Up @@ -219,7 +219,7 @@ mod tests {
let commit_hash = "d3b07384d113edec49eaa6238ad5ff00";
assert_eq!(
repo.format_commit_url(commit_hash),
format!("https://gitlab.com/proj/grp/repo/-/commit/{}", commit_hash)
format!("https://gitlab.com/proj/grp/repo/-/commit/{commit_hash}")
)
}

Expand Down Expand Up @@ -250,10 +250,7 @@ mod tests {
let commit_hash = "df41ac86f08a40e64c76062fd67e238522c14990";
assert_eq!(
repo.format_commit_url(commit_hash),
format!(
"https://git.sr.ht/~someuser/somerepo/commit/{}",
commit_hash
)
format!("https://git.sr.ht/~someuser/somerepo/commit/{commit_hash}")
)
}

Expand Down Expand Up @@ -287,7 +284,7 @@ mod tests {
let commit_hash = "1c072856ebf12419378c5098ad543c497197c6da";
assert_eq!(
repo.format_commit_url(commit_hash),
format!("https://codeberg.org/dnkl/foot/commit/{}", commit_hash)
format!("https://codeberg.org/dnkl/foot/commit/{commit_hash}")
)
}
}
2 changes: 1 addition & 1 deletion src/git_config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ impl GitConfig {
match config {
Some(mut config) => {
let config = config.snapshot().unwrap_or_else(|err| {
fatal(format!("Failed to read git config: {}", err));
fatal(format!("Failed to read git config: {err}"));
});
Some(Self {
config,
Expand Down
Loading

0 comments on commit 28bf556

Please sign in to comment.