1
0
mirror of https://github.com/o2sh/onefetch synced 2024-06-30 22:54:20 +00:00

cargo clippy pedantic

This commit is contained in:
o2sh 2023-05-28 21:37:31 +02:00
parent b4be64d93d
commit 0654eb957f
No known key found for this signature in database
GPG Key ID: C2414BD0092379D8
17 changed files with 59 additions and 67 deletions

View File

@ -15,7 +15,7 @@ fn bench_repo_info(c: &mut Criterion) {
b.iter(|| { b.iter(|| {
let result = black_box(build_info(&config)); let result = black_box(build_info(&config));
assert!(result.is_ok()); assert!(result.is_ok());
}) });
}); });
} }

View File

@ -50,7 +50,7 @@ impl std::fmt::Display for Author {
self.contribution, self.contribution,
self.name, self.name,
self.email, self.email,
format_number(self.nbr_of_commits, self.number_separator) format_number(&self.nbr_of_commits, self.number_separator)
) )
} else { } else {
write!( write!(
@ -58,7 +58,7 @@ impl std::fmt::Display for Author {
"{}% {} {}", "{}% {} {}",
self.contribution, self.contribution,
self.name, self.name,
format_number(self.nbr_of_commits, self.number_separator) format_number(&self.nbr_of_commits, self.number_separator)
) )
} }
} }

View File

@ -29,7 +29,7 @@ impl InfoField for CommitsInfo {
fn value(&self) -> String { fn value(&self) -> String {
format!( format!(
"{}{}", "{}{}",
format_number(self.number_of_commits, self.number_separator), format_number(&self.number_of_commits, self.number_separator),
self.is_shallow.then_some(" (shallow)").unwrap_or_default() self.is_shallow.then_some(" (shallow)").unwrap_or_default()
) )
} }

View File

@ -33,7 +33,7 @@ impl ContributorsInfo {
impl InfoField for ContributorsInfo { impl InfoField for ContributorsInfo {
fn value(&self) -> String { fn value(&self) -> String {
if self.total_number_of_authors > self.number_of_authors_to_display { if self.total_number_of_authors > self.number_of_authors_to_display {
format_number(self.total_number_of_authors, self.number_separator) format_number(&self.total_number_of_authors, self.number_separator)
} else { } else {
"".to_string() "".to_string()
} }

View File

@ -17,7 +17,7 @@ impl DependenciesInfo {
(m.number_of_dependencies != 0).then(|| { (m.number_of_dependencies != 0).then(|| {
format!( format!(
"{} ({})", "{} ({})",
format_number(m.number_of_dependencies, number_separator), format_number(&m.number_of_dependencies, number_separator),
m.manifest_type m.manifest_type
) )
}) })

View File

@ -153,7 +153,7 @@ impl InfoField for LanguagesInfo {
fn title(&self) -> String { fn title(&self) -> String {
let mut title: String = "Language".into(); let mut title: String = "Language".into();
if self.languages_with_percentage.len() > 1 { if self.languages_with_percentage.len() > 1 {
title.push('s') title.push('s');
} }
title title
} }

View File

@ -86,7 +86,7 @@ fn get_statistics(
fn filter_languages_on_type(types: &[LanguageType]) -> Vec<tokei::LanguageType> { fn filter_languages_on_type(types: &[LanguageType]) -> Vec<tokei::LanguageType> {
Language::iter() Language::iter()
.filter(|language| types.contains(&language.get_type())) .filter(|language| types.contains(&language.get_type()))
.map(|language| language.into()) .map(std::convert::Into::into)
.collect() .collect()
} }

View File

@ -113,7 +113,7 @@ mod test {
#[test] #[test]
fn test_is_license_file() { fn test_is_license_file() {
for file_name in LICENSE_FILES.iter() { for file_name in &LICENSE_FILES {
assert!(is_license_file(file_name)); assert!(is_license_file(file_name));
} }
assert!(!is_license_file("NOT_LICENSE")); assert!(!is_license_file("NOT_LICENSE"));

View File

@ -28,7 +28,7 @@ impl LocInfo {
#[typetag::serialize] #[typetag::serialize]
impl InfoField for LocInfo { impl InfoField for LocInfo {
fn value(&self) -> String { fn value(&self) -> String {
format_number(self.lines_of_code, self.number_separator) format_number(&self.lines_of_code, self.number_separator)
} }
fn title(&self) -> String { fn title(&self) -> String {

View File

@ -23,6 +23,7 @@ use crate::cli::{is_truecolor_terminal, CliOptions, NumberSeparator, When};
use crate::ui::get_ascii_colors; use crate::ui::get_ascii_colors;
use crate::ui::text_colors::TextColors; use crate::ui::text_colors::TextColors;
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use gix::sec::trust::Mapping;
use gix::Repository; use gix::Repository;
use num_format::ToFormattedString; use num_format::ToFormattedString;
use onefetch_manifest::Manifest; use onefetch_manifest::Manifest;
@ -77,7 +78,7 @@ impl std::fmt::Display for Info {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
//Title //Title
if let Some(title) = &self.title { if let Some(title) = &self.title {
write!(f, "{}", title)?; write!(f, "{title}")?;
} }
//Info lines //Info lines
@ -89,7 +90,7 @@ impl std::fmt::Display for Info {
info_field.should_color(), info_field.should_color(),
self.no_bold, self.no_bold,
&self.text_colors, &self.text_colors,
)? )?;
} }
//Palette //Palette
@ -119,7 +120,7 @@ pub fn build_info(cli_options: &CliOptions) -> Result<Info> {
dot_git_only: true, dot_git_only: true,
..Default::default() ..Default::default()
}, },
Default::default(), Mapping::default(),
)? )?
.to_thread_local(); .to_thread_local();
let repo_path = get_work_dir(&repo)?; let repo_path = get_work_dir(&repo)?;
@ -144,7 +145,7 @@ pub fn build_info(cli_options: &CliOptions) -> Result<Info> {
.ok() .ok()
.context("BUG: panic in language statistics thread")??; .context("BUG: panic in language statistics thread")??;
let manifest = get_manifest(&repo_path)?; let manifest = get_manifest(&repo_path)?;
let repo_url = get_repo_url(&repo)?; let repo_url = get_repo_url(&repo);
let commits = Commits::new( let commits = Commits::new(
&repo, &repo,
@ -174,7 +175,7 @@ pub fn build_info(cli_options: &CliOptions) -> Result<Info> {
let number_of_languages = cli_options.info.number_of_languages; let number_of_languages = cli_options.info.number_of_languages;
let number_of_authors = cli_options.info.number_of_authors; let number_of_authors = cli_options.info.number_of_authors;
Ok(InfoBuilder::new(cli_options)? Ok(InfoBuilder::new(cli_options)
.title(&repo, no_bold, &text_colors) .title(&repo, no_bold, &text_colors)
.project(&repo, &repo_url, &manifest, number_separator)? .project(&repo, &repo_url, &manifest, number_separator)?
.description(&manifest) .description(&manifest)
@ -201,13 +202,13 @@ pub fn build_info(cli_options: &CliOptions) -> Result<Info> {
} }
impl InfoBuilder { impl InfoBuilder {
fn new(cli_options: &CliOptions) -> Result<Self> { fn new(cli_options: &CliOptions) -> Self {
Ok(Self { Self {
title: None, title: None,
info_fields: Vec::new(), info_fields: Vec::new(),
disabled_fields: cli_options.info.disabled_fields.clone(), disabled_fields: cli_options.info.disabled_fields.clone(),
no_title: cli_options.info.no_title, no_title: cli_options.info.no_title,
}) }
} }
fn title(mut self, repo: &Repository, no_bold: bool, text_colors: &TextColors) -> Self { fn title(mut self, repo: &Repository, no_bold: bool, text_colors: &TextColors) -> Self {
@ -462,7 +463,7 @@ pub fn get_work_dir(repo: &gix::Repository) -> Result<std::path::PathBuf> {
} }
fn format_number<T: ToFormattedString + std::fmt::Display>( fn format_number<T: ToFormattedString + std::fmt::Display>(
number: T, number: &T,
number_separator: NumberSeparator, number_separator: NumberSeparator,
) -> String { ) -> String {
number.to_formatted_string(&number_separator.get_format()) number.to_formatted_string(&number_separator.get_format())
@ -474,43 +475,43 @@ mod tests {
use owo_colors::AnsiColors; use owo_colors::AnsiColors;
#[test] #[test]
fn test_get_style() -> Result<()> { fn test_get_style() {
let style = get_style(true, DynColors::Ansi(AnsiColors::Cyan)); let style = get_style(true, DynColors::Ansi(AnsiColors::Cyan));
assert_eq!( assert_eq!(
style, style,
Style::new().color(DynColors::Ansi(AnsiColors::Cyan)).bold() Style::new().color(DynColors::Ansi(AnsiColors::Cyan)).bold()
); );
Ok(())
} }
#[test] #[test]
fn test_get_style_no_bold() -> Result<()> { fn test_get_style_no_bold() {
let style = get_style(false, DynColors::Ansi(AnsiColors::Cyan)); let style = get_style(false, DynColors::Ansi(AnsiColors::Cyan));
assert_eq!(style, Style::new().color(DynColors::Ansi(AnsiColors::Cyan))); assert_eq!(style, Style::new().color(DynColors::Ansi(AnsiColors::Cyan)));
Ok(())
} }
#[test] #[test]
fn test_format_number() { fn test_format_number() {
assert_eq!( assert_eq!(
&format_number(1_000_000, NumberSeparator::Comma), &format_number(&1_000_000, NumberSeparator::Comma),
"1,000,000" "1,000,000"
); );
assert_eq!( assert_eq!(
&format_number(1_000_000, NumberSeparator::Space), &format_number(&1_000_000, NumberSeparator::Space),
"1\u{202f}000\u{202f}000" "1\u{202f}000\u{202f}000"
); );
assert_eq!( assert_eq!(
&format_number(1_000_000, NumberSeparator::Underscore), &format_number(&1_000_000, NumberSeparator::Underscore),
"1_000_000" "1_000_000"
); );
assert_eq!(&format_number(1_000_000, NumberSeparator::Plain), "1000000"); assert_eq!(
&format_number(&1_000_000, NumberSeparator::Plain),
"1000000"
);
} }
#[test] #[test]
fn test_info_style_info() -> Result<()> { fn test_info_style_info() {
let text_colors = let text_colors = TextColors::new(&[0, 0, 0, 0, 0, 0], DynColors::Ansi(AnsiColors::Blue));
TextColors::new(&vec![0, 0, 0, 0, 0, 0], DynColors::Ansi(AnsiColors::Blue));
let info_text = style_info("foo", &text_colors, false); let info_text = style_info("foo", &text_colors, false);
assert_eq!(info_text, "foo"); assert_eq!(info_text, "foo");
@ -519,13 +520,11 @@ mod tests {
let info_text = style_info("foo", &text_colors, true); let info_text = style_info("foo", &text_colors, true);
// Rendered text: black `foo` // Rendered text: black `foo`
assert_eq!(info_text, "\u{1b}[30mfoo\u{1b}[0m"); assert_eq!(info_text, "\u{1b}[30mfoo\u{1b}[0m");
Ok(())
} }
#[test] #[test]
fn test_info_style_subtitle() -> Result<()> { fn test_info_style_subtitle() {
let text_colors = let text_colors = TextColors::new(&[0, 0, 0, 0, 15, 0], DynColors::Ansi(AnsiColors::Blue));
TextColors::new(&vec![0, 0, 0, 0, 15, 0], DynColors::Ansi(AnsiColors::Blue));
let subtitle_text = style_subtitle("foo", &text_colors, false); let subtitle_text = style_subtitle("foo", &text_colors, false);
assert_eq!( assert_eq!(
@ -533,6 +532,5 @@ mod tests {
// Rendered text: black `foo` and bright white colon // Rendered text: black `foo` and bright white colon
"\u{1b}[30;1mfoo\u{1b}[0m\u{1b}[97;1m:\u{1b}[0m" "\u{1b}[30;1mfoo\u{1b}[0m\u{1b}[97;1m:\u{1b}[0m"
); );
Ok(())
} }
} }

View File

@ -45,7 +45,7 @@ fn get_pending_changes(repo: &git2::Repository) -> Result<String> {
let mut result = String::new(); let mut result = String::new();
if modified > 0 { if modified > 0 {
result = format!("{modified}+-") result = format!("{modified}+-");
} }
if added > 0 { if added > 0 {

View File

@ -47,7 +47,7 @@ fn get_repo_name(repo_url: &str, manifest: Option<&Manifest>) -> Result<String>
.with_extension("") .with_extension("")
.file_name() .file_name()
.map(OsStr::to_string_lossy) .map(OsStr::to_string_lossy)
.map(|s| s.into_owned()) .map(std::borrow::Cow::into_owned)
.unwrap_or_default(); .unwrap_or_default();
if repo_name.is_empty() { if repo_name.is_empty() {
@ -82,7 +82,7 @@ impl std::fmt::Display for ProjectInfo {
1 => "1 branch".into(), 1 => "1 branch".into(),
_ => format!( _ => format!(
"{} branches", "{} branches",
format_number(self.number_of_branches, self.number_separator) format_number(&self.number_of_branches, self.number_separator)
), ),
}; };
@ -91,7 +91,7 @@ impl std::fmt::Display for ProjectInfo {
1 => "1 tag".into(), 1 => "1 tag".into(),
_ => format!( _ => format!(
"{} tags", "{} tags",
format_number(self.number_of_tags, self.number_separator) format_number(&self.number_of_tags, self.number_separator)
), ),
}; };
@ -198,7 +198,7 @@ mod test {
#[test] #[test]
fn test_display_project_info_when_no_repo_name() { fn test_display_project_info_when_no_repo_name() {
let project_info = ProjectInfo { let project_info = ProjectInfo {
repo_name: "".to_string(), repo_name: String::new(),
number_of_branches: 0, number_of_branches: 0,
number_of_tags: 0, number_of_tags: 0,
number_separator: NumberSeparator::Plain, number_separator: NumberSeparator::Plain,

View File

@ -53,7 +53,7 @@ impl std::fmt::Display for SizeInfo {
f, f,
"{} ({} files)", "{} ({} files)",
self.repo_size, self.repo_size,
format_number(self.file_count, self.number_separator) format_number(&self.file_count, self.number_separator)
) )
} }
} }

View File

@ -124,14 +124,14 @@ mod tests {
assert!(title.to_string().contains('~')); assert!(title.to_string().contains('~'));
assert!(title.to_string().contains("git version 2.37.2")); assert!(title.to_string().contains("git version 2.37.2"));
title.git_version = "".to_string(); title.git_version = String::new();
assert!(title.to_string().contains("onefetch-committer-name")); assert!(title.to_string().contains("onefetch-committer-name"));
assert!(!title.to_string().contains('~')); assert!(!title.to_string().contains('~'));
assert!(!title.to_string().contains("git version 2.37.2")); assert!(!title.to_string().contains("git version 2.37.2"));
title.git_username = "".to_string(); title.git_username = String::new();
let expected_title = "".to_string(); let expected_title = String::new();
assert_eq!(format!("{}", title), expected_title); assert_eq!(format!("{title}"), expected_title);
Ok(()) Ok(())
} }

View File

@ -1,5 +1,4 @@
use crate::info::utils::info_field::InfoField; use crate::info::utils::info_field::InfoField;
use anyhow::Result;
use gix::Repository; use gix::Repository;
use regex::Regex; use regex::Regex;
use serde::Serialize; use serde::Serialize;
@ -17,11 +16,11 @@ impl UrlInfo {
} }
} }
pub fn get_repo_url(repo: &Repository) -> Result<String> { pub fn get_repo_url(repo: &Repository) -> String {
let config = repo.config_snapshot(); let config = repo.config_snapshot();
let remotes = match config.plumbing().sections_by_name("remote") { let remotes = match config.plumbing().sections_by_name("remote") {
Some(sections) => sections, Some(sections) => sections,
None => return Ok(Default::default()), None => return String::default(),
}; };
let mut remote_url: Option<String> = None; let mut remote_url: Option<String> = None;
@ -36,17 +35,15 @@ pub fn get_repo_url(repo: &Repository) -> Result<String> {
} }
} }
let remote_url = match remote_url { match remote_url {
Some(url) => remove_token_from_url(url), Some(url) => remove_token_from_url(&url),
None => return Ok(Default::default()), None => String::default(),
}; }
Ok(remote_url)
} }
fn remove_token_from_url(url: String) -> String { fn remove_token_from_url(url: &str) -> String {
let pattern = Regex::new(r"(https?://)([^@]+@)").unwrap(); let pattern = Regex::new(r"(https?://)([^@]+@)").unwrap();
let replaced_url = pattern.replace(&url, "$1").to_string(); let replaced_url = pattern.replace(url, "$1").to_string();
replaced_url replaced_url
} }
@ -80,16 +77,14 @@ mod test {
#[test] #[test]
fn test_token_removal_github() { fn test_token_removal_github() {
let remote_url = let remote_url =
"https://1234567890abcdefghijklmnopqrstuvwxyz@github.com/jim4067/onefetch.git" "https://1234567890abcdefghijklmnopqrstuvwxyz@github.com/jim4067/onefetch.git";
.to_string();
let res_url = remove_token_from_url(remote_url); let res_url = remove_token_from_url(remote_url);
assert_eq!("https://github.com/jim4067/onefetch.git", res_url); assert_eq!("https://github.com/jim4067/onefetch.git", res_url);
} }
#[test] #[test]
fn test_token_removal_gitlab() { fn test_token_removal_gitlab() {
let remote_url = let remote_url = "https://john:abc123personaltoken@gitlab.com/jim4067/myproject.git";
"https://john:abc123personaltoken@gitlab.com/jim4067/myproject.git".to_string();
let res_url = remove_token_from_url(remote_url); let res_url = remove_token_from_url(remote_url);
assert_eq!("https://gitlab.com/jim4067/myproject.git", res_url); assert_eq!("https://gitlab.com/jim4067/myproject.git", res_url);
} }

View File

@ -146,10 +146,9 @@ fn get_no_bots_regex(no_bots: &Option<Option<MyRegex>>) -> Result<Option<MyRegex
} }
fn is_bot(author_name: &BString, bot_regex_pattern: &Option<MyRegex>) -> bool { fn is_bot(author_name: &BString, bot_regex_pattern: &Option<MyRegex>) -> bool {
bot_regex_pattern bot_regex_pattern.as_ref().map_or(false, |regex| {
.as_ref() regex.0.is_match(author_name.to_str_lossy().as_ref())
.map(|regex| regex.0.is_match(author_name.to_str_lossy().as_ref())) })
.unwrap_or(false)
} }
#[cfg(test)] #[cfg(test)]

View File

@ -65,10 +65,10 @@ impl<W: Write> Printer<W> {
match &self.output { match &self.output {
Some(format) => match format { Some(format) => match format {
SerializationFormat::Json => { SerializationFormat::Json => {
writeln!(self.writer, "{}", serde_json::to_string_pretty(&self.info)?)? writeln!(self.writer, "{}", serde_json::to_string_pretty(&self.info)?)?;
} }
SerializationFormat::Yaml => { SerializationFormat::Yaml => {
writeln!(self.writer, "{}", serde_yaml::to_string(&self.info)?)? writeln!(self.writer, "{}", serde_yaml::to_string(&self.info)?)?;
} }
}, },
None => { None => {
@ -104,7 +104,7 @@ impl<W: Write> Printer<W> {
loop { loop {
match (logo_lines.next(), info_lines.next()) { match (logo_lines.next(), info_lines.next()) {
(Some(logo_line), Some(info_line)) => { (Some(logo_line), Some(info_line)) => {
writeln!(buf, "{logo_line}{center_pad}{info_line:^}")? writeln!(buf, "{logo_line}{center_pad}{info_line:^}")?;
} }
(Some(logo_line), None) => writeln!(buf, "{logo_line}")?, (Some(logo_line), None) => writeln!(buf, "{logo_line}")?,
(None, Some(info_line)) => writeln!( (None, Some(info_line)) => writeln!(