Browse Source

cargo clippy pedantic

pull/1579/head
o2sh 7 months ago
parent
commit
dbb91b6e77
No known key found for this signature in database
GPG Key ID: D099D76E63AD9E67
  1. 12
      ascii/src/lib.rs
  2. 26
      build.rs
  3. 4
      manifest/src/lib.rs
  4. 6
      src/cli.rs
  5. 2
      src/info/authors.rs
  6. 6
      src/info/churn.rs
  7. 2
      src/info/contributors.rs
  8. 9
      src/info/git/metrics.rs
  9. 12
      src/info/git/mod.rs
  10. 8
      src/info/head.rs
  11. 3
      src/info/license.rs

12
ascii/src/lib.rs

@ -205,8 +205,7 @@ impl<'a> Tokens<'a> {
let mut whole_string = String::new(); let mut whole_string = String::new();
let mut color = &DynColors::Ansi(AnsiColors::Default); let mut color = &DynColors::Ansi(AnsiColors::Default);
self.truncate(start, end).for_each(|token| { self.truncate(start, end).for_each(|token| match token {
match token {
Token::Char(chr) => { Token::Char(chr) => {
width = width.saturating_sub(1); width = width.saturating_sub(1);
colored_segment.push(chr); colored_segment.push(chr);
@ -220,9 +219,8 @@ impl<'a> Tokens<'a> {
} }
Token::Space => { Token::Space => {
width = width.saturating_sub(1); width = width.saturating_sub(1);
colored_segment.push(' ') colored_segment.push(' ');
} }
};
}); });
add_styled_segment(&mut whole_string, &colored_segment, *color, bold); add_styled_segment(&mut whole_string, &colored_segment, *color, bold);
@ -267,15 +265,15 @@ fn token<R>(s: &str, predicate: impl FnOnce(char) -> Option<R>) -> ParseResult<R
/// Parses a color indicator of the format `{n}` where `n` is a digit. /// Parses a color indicator of the format `{n}` where `n` is a digit.
fn color_token(s: &str) -> ParseResult<Token> { fn color_token(s: &str) -> ParseResult<Token> {
let (s, _) = token(s, succeed_when(|c| c == '{'))?; let (s, ()) = token(s, succeed_when(|c| c == '{'))?;
let (s, color_index) = token(s, |c| c.to_digit(10))?; let (s, color_index) = token(s, |c| c.to_digit(10))?;
let (s, _) = token(s, succeed_when(|c| c == '}'))?; let (s, ()) = token(s, succeed_when(|c| c == '}'))?;
Some((s, Token::Color(color_index))) Some((s, Token::Color(color_index)))
} }
/// Parses a space. /// Parses a space.
fn space_token(s: &str) -> ParseResult<Token> { fn space_token(s: &str) -> ParseResult<Token> {
token(s, succeed_when(|c| c == ' ')).map(|(s, _)| (s, Token::Space)) token(s, succeed_when(|c| c == ' ')).map(|(s, ())| (s, Token::Space))
} }
/// Parses any arbitrary character. This cannot fail. /// Parses any arbitrary character. This cannot fail.

26
build.rs

@ -1,10 +1,10 @@
use lazy_static::lazy_static;
use regex::Regex; use regex::Regex;
use std::collections::HashMap; use std::collections::HashMap;
use std::env; use std::env;
use std::error::Error; use std::error::Error;
use std::fs::{self, File}; use std::fs::{self, File};
use std::path::Path; use std::path::Path;
use std::sync::LazyLock;
use tera::{Context, Tera}; use tera::{Context, Tera};
fn main() -> Result<(), Box<dyn Error>> { fn main() -> Result<(), Box<dyn Error>> {
@ -37,12 +37,9 @@ fn strip_color_tokens_filter(
value: &tera::Value, value: &tera::Value,
_args: &HashMap<String, tera::Value>, _args: &HashMap<String, tera::Value>,
) -> tera::Result<tera::Value> { ) -> tera::Result<tera::Value> {
lazy_static! { static COLOR_INDEX_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\{\d+\}").unwrap());
static ref COLOR_INDEX_REGEX: Regex = Regex::new(r"\{\d+\}").unwrap(); let tera::Value::String(s) = value else {
} return Err(tera::Error::msg("expected string"));
let s = match value {
tera::Value::String(s) => s,
_ => return Err(tera::Error::msg("expected string")),
}; };
Ok(tera::Value::String( Ok(tera::Value::String(
COLOR_INDEX_REGEX.replace_all(s, "").to_string(), COLOR_INDEX_REGEX.replace_all(s, "").to_string(),
@ -53,20 +50,17 @@ fn hex_to_rgb_filter(
value: &tera::Value, value: &tera::Value,
_args: &HashMap<String, tera::Value>, _args: &HashMap<String, tera::Value>,
) -> tera::Result<tera::Value> { ) -> tera::Result<tera::Value> {
let hex_string = match value { let tera::Value::String(hex_string) = value else {
tera::Value::String(s) => s, return Err(tera::Error::msg("expected string"));
_ => return Err(tera::Error::msg("expected string")),
}; };
let hex_string = match hex_string.strip_prefix('#') { let Some(hex_string) = hex_string.strip_prefix('#') else {
Some(s) => s, return Err(tera::Error::msg("expected hex string starting with `#`"));
None => return Err(tera::Error::msg("expected hex string starting with `#`")),
}; };
if hex_string.len() != 6 { if hex_string.len() != 6 {
return Err(tera::Error::msg("expected a 6 digit hex string")); return Err(tera::Error::msg("expected a 6 digit hex string"));
} }
let channel_bytes = match u32::from_str_radix(hex_string, 16) { let Ok(channel_bytes) = u32::from_str_radix(hex_string, 16) else {
Ok(n) => n, return Err(tera::Error::msg("expected a valid hex string"));
Err(_) => return Err(tera::Error::msg("expected a valid hex string")),
}; };
let r = (channel_bytes >> 16) & 0xFF; let r = (channel_bytes >> 16) & 0xFF;
let g = (channel_bytes >> 8) & 0xFF; let g = (channel_bytes >> 8) & 0xFF;

4
manifest/src/lib.rs

@ -45,7 +45,7 @@ fn parse_cargo_manifest(path: &Path) -> Result<Manifest> {
let m = cargo_toml::Manifest::from_path(path) let m = cargo_toml::Manifest::from_path(path)
.with_context(|| format!("Failed to parse Cargo.toml at '{}'", path.display()))?; .with_context(|| format!("Failed to parse Cargo.toml at '{}'", path.display()))?;
let package = m.package.context("Not a package (only a workspace)")?; let package = m.package.context("Not a package (only a workspace)")?;
let description = package.description().map(|v| v.into()); let description = package.description().map(Into::into);
Ok(Manifest { Ok(Manifest {
manifest_type: ManifestType::Cargo, manifest_type: ManifestType::Cargo,
@ -53,7 +53,7 @@ fn parse_cargo_manifest(path: &Path) -> Result<Manifest> {
name: package.name.clone(), name: package.name.clone(),
description, description,
version: package.version().into(), version: package.version().into(),
license: package.license().map(|x| x.into()), license: package.license().map(Into::into),
}) })
} }

6
src/cli.rs

@ -274,7 +274,7 @@ impl Default for InfoCliOptions {
impl Default for TextForamttingCliOptions { impl Default for TextForamttingCliOptions {
fn default() -> Self { fn default() -> Self {
TextForamttingCliOptions { TextForamttingCliOptions {
text_colors: Default::default(), text_colors: Vec::default(),
iso_time: Default::default(), iso_time: Default::default(),
number_separator: NumberSeparator::Plain, number_separator: NumberSeparator::Plain,
no_bold: Default::default(), no_bold: Default::default(),
@ -296,7 +296,7 @@ impl Default for ImageCliOptions {
fn default() -> Self { fn default() -> Self {
ImageCliOptions { ImageCliOptions {
image: Option::default(), image: Option::default(),
image_protocol: Default::default(), image_protocol: Option::default(),
color_resolution: 16, color_resolution: 16,
} }
} }
@ -353,7 +353,7 @@ pub enum NumberSeparator {
} }
impl NumberSeparator { impl NumberSeparator {
fn separator(&self) -> &'static str { fn separator(self) -> &'static str {
match self { match self {
Self::Plain => "", Self::Plain => "",
Self::Comma => ",", Self::Comma => ",",

2
src/info/authors.rs

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

6
src/info/churn.rs

@ -87,14 +87,14 @@ fn compute_file_churns(
Ok(number_of_commits_by_file_path_sorted Ok(number_of_commits_by_file_path_sorted
.into_iter() .into_iter()
.filter_map(|(file_path, nbr_of_commits)| { .filter_map(|(file_path, nbr_of_commits)| {
if !glob_set.is_match(file_path.to_string()) { if glob_set.is_match(file_path.to_string()) {
None
} else {
Some(FileChurn::new( Some(FileChurn::new(
file_path.to_string(), file_path.to_string(),
*nbr_of_commits, *nbr_of_commits,
number_separator, number_separator,
)) ))
} else {
None
} }
}) })
.take(number_of_file_churns_to_display) .take(number_of_file_churns_to_display)

2
src/info/contributors.rs

@ -32,7 +32,7 @@ impl InfoField for ContributorsInfo {
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() String::new()
} }
} }

9
src/info/git/metrics.rs

@ -1,5 +1,4 @@
use super::sig::Sig; use super::sig::Sig;
use anyhow::Result;
use gix::bstr::BString; use gix::bstr::BString;
use gix::date::Time; use gix::date::Time;
use std::collections::HashMap; use std::collections::HashMap;
@ -21,7 +20,7 @@ impl GitMetrics {
churn_pool_size: usize, churn_pool_size: usize,
time_of_first_commit: Option<Time>, time_of_first_commit: Option<Time>,
time_of_most_recent_commit: Option<Time>, time_of_most_recent_commit: Option<Time>,
) -> Result<Self> { ) -> Self {
let total_number_of_commits = number_of_commits_by_signature.values().sum(); let total_number_of_commits = number_of_commits_by_signature.values().sum();
let total_number_of_authors = number_of_commits_by_signature.len(); let total_number_of_authors = number_of_commits_by_signature.len();
@ -30,14 +29,14 @@ impl GitMetrics {
.and_then(|a| time_of_most_recent_commit.map(|b| (a, b))) .and_then(|a| time_of_most_recent_commit.map(|b| (a, b)))
.unwrap_or_default(); .unwrap_or_default();
Ok(Self { Self {
number_of_commits_by_signature, number_of_commits_by_signature,
number_of_commits_by_file_path, number_of_commits_by_file_path,
total_number_of_authors, total_number_of_authors,
total_number_of_commits, total_number_of_commits,
churn_pool_size, churn_pool_size,
time_of_first_commit,
time_of_most_recent_commit, time_of_most_recent_commit,
}) time_of_first_commit,
}
} }
} }

12
src/info/git/mod.rs

@ -33,7 +33,7 @@ pub fn traverse_commit_graph(
let total_number_of_commits = Arc::new(AtomicUsize::default()); let total_number_of_commits = Arc::new(AtomicUsize::default());
let num_threads = std::thread::available_parallelism() let num_threads = std::thread::available_parallelism()
.map(|p| p.get()) .map(std::num::NonZero::get)
.unwrap_or(1); .unwrap_or(1);
let commit_graph = repo.commit_graph().ok(); let commit_graph = repo.commit_graph().ok();
let can_use_author_threads = num_threads > 1 && commit_graph.is_some(); let can_use_author_threads = num_threads > 1 && commit_graph.is_some();
@ -54,7 +54,7 @@ pub fn traverse_commit_graph(
&is_traversal_complete, &is_traversal_complete,
&total_number_of_commits, &total_number_of_commits,
min_churn_pool_size, min_churn_pool_size,
)?; );
let author_threads = can_use_author_threads let author_threads = can_use_author_threads
.then(|| get_author_channel(repo, num_threads, no_bots.clone(), &mailmap)); .then(|| get_author_channel(repo, num_threads, no_bots.clone(), &mailmap));
@ -117,7 +117,7 @@ pub fn traverse_commit_graph(
churn_pool_size, churn_pool_size,
time_of_first_commit, time_of_first_commit,
time_of_most_recent_commit, time_of_most_recent_commit,
)?; );
Ok(git_metrics) Ok(git_metrics)
} }
@ -177,7 +177,7 @@ fn get_churn_channel(
is_traversal_complete: &Arc<AtomicBool>, is_traversal_complete: &Arc<AtomicBool>,
total_number_of_commits: &Arc<AtomicUsize>, total_number_of_commits: &Arc<AtomicUsize>,
max_churn_pool_size: Option<usize>, max_churn_pool_size: Option<usize>,
) -> Result<(JoinHandle<Result<ChurnPair>>, Sender<ObjectId>)> { ) -> (JoinHandle<Result<ChurnPair>>, Sender<ObjectId>) {
let (tx, rx) = channel::<gix::hash::ObjectId>(); let (tx, rx) = channel::<gix::hash::ObjectId>();
let thread = std::thread::spawn({ let thread = std::thread::spawn({
let repo = repo.clone(); let repo = repo.clone();
@ -209,7 +209,7 @@ fn get_churn_channel(
} }
}); });
Ok((thread, tx)) (thread, tx)
} }
fn should_break( fn should_break(
@ -261,7 +261,7 @@ fn compute_diff_with_parent(
let new_tree = commit.tree()?; let new_tree = commit.tree()?;
let changes = let changes =
repo.diff_tree_to_tree(&old_tree, &new_tree, Options::default().with_rewrites(None))?; repo.diff_tree_to_tree(&old_tree, &new_tree, Options::default().with_rewrites(None))?;
for change in changes.iter() { for change in &changes {
let is_file_change = match change { let is_file_change = match change {
Change::Addition { entry_mode, .. } | Change::Modification { entry_mode, .. } => { Change::Addition { entry_mode, .. } | Change::Modification { entry_mode, .. } => {
entry_mode.is_blob() entry_mode.is_blob()

8
src/info/head.rs

@ -21,16 +21,16 @@ impl HeadRefs {
impl std::fmt::Display for HeadRefs { impl std::fmt::Display for HeadRefs {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
if !self.refs.is_empty() { if self.refs.is_empty() {
write!(f, "{}", self.short_commit_id)
} else {
let refs_str = self let refs_str = self
.refs .refs
.iter() .iter()
.map(|ref_name| ref_name.as_str()) .map(String::as_str)
.collect::<Vec<&str>>() .collect::<Vec<&str>>()
.join(", "); .join(", ");
write!(f, "{} ({})", self.short_commit_id, refs_str) write!(f, "{} ({})", self.short_commit_id, refs_str)
} else {
write!(f, "{}", self.short_commit_id)
} }
} }
} }

3
src/info/license.rs

@ -39,8 +39,7 @@ impl Detector {
&& entry && entry
.file_name() .file_name()
.map(OsStr::to_string_lossy) .map(OsStr::to_string_lossy)
.map(is_license_file) .is_some_and(is_license_file)
.unwrap_or_default()
}) })
.filter_map(|entry| { .filter_map(|entry| {
let contents = fs::read_to_string(entry).unwrap_or_default(); let contents = fs::read_to_string(entry).unwrap_or_default();

Loading…
Cancel
Save