diff --git a/asyncgit/src/commit_files.rs b/asyncgit/src/commit_files.rs index 265b38ee..aa8c0d96 100644 --- a/asyncgit/src/commit_files.rs +++ b/asyncgit/src/commit_files.rs @@ -35,11 +35,8 @@ impl AsyncCommitFiles { ) -> Result> { let c = self.current.lock()?; - if let Some(c) = c.as_ref() { - Ok(Some((c.0, c.1.clone()))) - } else { - Ok(None) - } + c.as_ref() + .map_or(Ok(None), |c| Ok(Some((c.0, c.1.clone())))) } /// @@ -71,7 +68,7 @@ impl AsyncCommitFiles { self.pending.fetch_add(1, Ordering::Relaxed); rayon_core::spawn(move || { - Self::fetch_helper(id, arc_current) + Self::fetch_helper(id, &arc_current) .expect("failed to fetch"); arc_pending.fetch_sub(1, Ordering::Relaxed); @@ -86,7 +83,7 @@ impl AsyncCommitFiles { fn fetch_helper( id: CommitId, - arc_current: Arc< + arc_current: &Arc< Mutex>>, >, ) -> Result<()> { diff --git a/asyncgit/src/diff.rs b/asyncgit/src/diff.rs index 4541c412..92797c8c 100644 --- a/asyncgit/src/diff.rs +++ b/asyncgit/src/diff.rs @@ -110,10 +110,10 @@ impl AsyncDiff { self.pending.fetch_add(1, Ordering::Relaxed); rayon_core::spawn(move || { - let notify = AsyncDiff::get_diff_helper( + let notify = Self::get_diff_helper( params, - arc_last, - arc_current, + &arc_last, + &arc_current, hash, ); @@ -141,18 +141,18 @@ impl AsyncDiff { fn get_diff_helper( params: DiffParams, - arc_last: Arc< + arc_last: &Arc< Mutex>>, >, - arc_current: Arc>>, + arc_current: &Arc>>, hash: u64, ) -> Result { let res = match params.diff_type { DiffType::Stage => { - sync::diff::get_diff(CWD, params.path.clone(), true)? + sync::diff::get_diff(CWD, ¶ms.path, true)? } DiffType::WorkDir => { - sync::diff::get_diff(CWD, params.path.clone(), false)? + sync::diff::get_diff(CWD, ¶ms.path, false)? } DiffType::Commit(id) => sync::diff::get_diff_commit( CWD, diff --git a/asyncgit/src/error.rs b/asyncgit/src/error.rs index 608b5cc9..e83bed75 100644 --- a/asyncgit/src/error.rs +++ b/asyncgit/src/error.rs @@ -38,6 +38,6 @@ pub type Result = std::result::Result; impl From> for Error { fn from(error: std::sync::PoisonError) -> Self { - Error::Generic(format!("poison error: {}", error)) + Self::Generic(format!("poison error: {}", error)) } } diff --git a/asyncgit/src/fetch.rs b/asyncgit/src/fetch.rs index cd255291..58130c86 100644 --- a/asyncgit/src/fetch.rs +++ b/asyncgit/src/fetch.rs @@ -74,7 +74,7 @@ impl AsyncFetch { } self.set_request(¶ms)?; - RemoteProgress::set_progress(self.progress.clone(), None)?; + RemoteProgress::set_progress(&self.progress, None)?; let arc_state = Arc::clone(&self.state); let arc_res = Arc::clone(&self.last_result); @@ -104,9 +104,9 @@ impl AsyncFetch { handle.join().expect("joining thread failed"); - Self::set_result(arc_res, res).expect("result error"); + Self::set_result(&arc_res, res).expect("result error"); - Self::clear_request(arc_state).expect("clear error"); + Self::clear_request(&arc_state).expect("clear error"); sender .send(AsyncNotification::Fetch) @@ -131,7 +131,7 @@ impl AsyncFetch { } fn clear_request( - state: Arc>>, + state: &Arc>>, ) -> Result<()> { let mut state = state.lock()?; @@ -141,7 +141,7 @@ impl AsyncFetch { } fn set_result( - arc_result: Arc>>, + arc_result: &Arc>>, res: Result, ) -> Result<()> { let mut last_res = arc_result.lock()?; diff --git a/asyncgit/src/lib.rs b/asyncgit/src/lib.rs index 6c635f21..be2fb9bd 100644 --- a/asyncgit/src/lib.rs +++ b/asyncgit/src/lib.rs @@ -8,29 +8,23 @@ #![deny(clippy::all)] #![deny(clippy::cargo)] #![deny(clippy::pedantic)] -//TODO: -// #![deny(clippy::nursery)] +#![deny(clippy::nursery)] #![deny(clippy::unwrap_used)] #![deny(clippy::panic)] #![deny(clippy::perf)] #![deny(clippy::match_like_matches_macro)] #![deny(clippy::needless_update)] #![allow(clippy::module_name_repetitions)] +#![allow(clippy::must_use_candidate)] //TODO: get this in someday since expect still leads us to crashes sometimes // #![deny(clippy::expect_used)] //TODO: -#![allow(clippy::needless_pass_by_value)] -#![allow(clippy::must_use_candidate)] #![allow(clippy::missing_errors_doc)] -#![allow(clippy::map_unwrap_or)] -#![allow(clippy::option_if_let_else)] -#![allow(clippy::manual_ok_or)] -#![allow(clippy::doc_markdown)] +#![allow(clippy::too_many_lines)] #![allow(clippy::cast_possible_wrap)] #![allow(clippy::cast_sign_loss)] #![allow(clippy::cast_possible_truncation)] #![allow(clippy::cast_precision_loss)] -#![allow(clippy::too_many_lines)] pub mod cached; mod commit_files; diff --git a/asyncgit/src/progress.rs b/asyncgit/src/progress.rs index 19680c26..c96b4c71 100644 --- a/asyncgit/src/progress.rs +++ b/asyncgit/src/progress.rs @@ -18,11 +18,11 @@ impl ProgressPercent { Self { progress } } /// - pub fn empty() -> Self { + pub const fn empty() -> Self { Self { progress: 0 } } /// - pub fn full() -> Self { + pub const fn full() -> Self { Self { progress: 100 } } } diff --git a/asyncgit/src/push.rs b/asyncgit/src/push.rs index 02c56f83..2af757bd 100644 --- a/asyncgit/src/push.rs +++ b/asyncgit/src/push.rs @@ -76,7 +76,7 @@ impl AsyncPush { } self.set_request(¶ms)?; - RemoteProgress::set_progress(self.progress.clone(), None)?; + RemoteProgress::set_progress(&self.progress, None)?; let arc_state = Arc::clone(&self.state); let arc_res = Arc::clone(&self.last_result); @@ -108,9 +108,9 @@ impl AsyncPush { handle.join().expect("joining thread failed"); - Self::set_result(arc_res, res).expect("result error"); + Self::set_result(&arc_res, res).expect("result error"); - Self::clear_request(arc_state).expect("clear error"); + Self::clear_request(&arc_state).expect("clear error"); sender .send(AsyncNotification::Push) @@ -135,7 +135,7 @@ impl AsyncPush { } fn clear_request( - state: Arc>>, + state: &Arc>>, ) -> Result<()> { let mut state = state.lock()?; @@ -145,7 +145,7 @@ impl AsyncPush { } fn set_result( - arc_result: Arc>>, + arc_result: &Arc>>, res: Result<()>, ) -> Result<()> { let mut last_res = arc_result.lock()?; diff --git a/asyncgit/src/push_tags.rs b/asyncgit/src/push_tags.rs index cfbe5a73..d0e2bbc7 100644 --- a/asyncgit/src/push_tags.rs +++ b/asyncgit/src/push_tags.rs @@ -72,7 +72,7 @@ impl AsyncPushTags { } self.set_request(¶ms)?; - RemoteProgress::set_progress(self.progress.clone(), None)?; + RemoteProgress::set_progress(&self.progress, None)?; let arc_state = Arc::clone(&self.state); let arc_res = Arc::clone(&self.last_result); @@ -98,9 +98,9 @@ impl AsyncPushTags { handle.join().expect("joining thread failed"); - Self::set_result(arc_res, res).expect("result error"); + Self::set_result(&arc_res, res).expect("result error"); - Self::clear_request(arc_state).expect("clear error"); + Self::clear_request(&arc_state).expect("clear error"); sender .send(AsyncNotification::PushTags) @@ -125,7 +125,7 @@ impl AsyncPushTags { } fn clear_request( - state: Arc>>, + state: &Arc>>, ) -> Result<()> { let mut state = state.lock()?; @@ -135,7 +135,7 @@ impl AsyncPushTags { } fn set_result( - arc_result: Arc>>, + arc_result: &Arc>>, res: Result<()>, ) -> Result<()> { let mut last_res = arc_result.lock()?; diff --git a/asyncgit/src/remote_progress.rs b/asyncgit/src/remote_progress.rs index 8df50bca..79c15911 100644 --- a/asyncgit/src/remote_progress.rs +++ b/asyncgit/src/remote_progress.rs @@ -52,12 +52,12 @@ impl RemoteProgress { } /// - pub fn get_progress_percent(&self) -> u8 { + pub const fn get_progress_percent(&self) -> u8 { self.progress.progress } pub(crate) fn set_progress( - progress: Arc>>, + progress: &Arc>>, state: Option, ) -> Result<()> { let mut progress = progress.lock()?; @@ -81,7 +81,7 @@ impl RemoteProgress { match incoming { Ok(update) => { Self::set_progress( - progress.clone(), + &progress, Some(update.clone()), ) .expect("set progress failed"); @@ -116,26 +116,22 @@ impl From for RemoteProgress { current, total, } => match stage { - PackBuilderStage::AddingObjects => { - RemoteProgress::new( - RemoteProgressState::PackingAddingObject, - current, - total, - ) - } - PackBuilderStage::Deltafication => { - RemoteProgress::new( - RemoteProgressState::PackingDeltafiction, - current, - total, - ) - } + PackBuilderStage::AddingObjects => Self::new( + RemoteProgressState::PackingAddingObject, + current, + total, + ), + PackBuilderStage::Deltafication => Self::new( + RemoteProgressState::PackingDeltafiction, + current, + total, + ), }, ProgressNotification::PushTransfer { current, total, .. - } => RemoteProgress::new( + } => Self::new( RemoteProgressState::Pushing, current, total, @@ -144,12 +140,12 @@ impl From for RemoteProgress { objects, total_objects, .. - } => RemoteProgress::new( + } => Self::new( RemoteProgressState::Transfer, objects, total_objects, ), - _ => RemoteProgress::new(RemoteProgressState::Done, 1, 1), + _ => Self::new(RemoteProgressState::Done, 1, 1), } } } diff --git a/asyncgit/src/revlog.rs b/asyncgit/src/revlog.rs index 87958ecf..55495948 100644 --- a/asyncgit/src/revlog.rs +++ b/asyncgit/src/revlog.rs @@ -121,9 +121,9 @@ impl AsyncLog { rayon_core::spawn(move || { scope_time!("async::revlog"); - AsyncLog::fetch_helper( - arc_current, - arc_background, + Self::fetch_helper( + &arc_current, + &arc_background, &sender, ) .expect("failed to fetch"); @@ -137,8 +137,8 @@ impl AsyncLog { } fn fetch_helper( - arc_current: Arc>>, - arc_background: Arc, + arc_current: &Arc>>, + arc_background: &Arc, sender: &Sender, ) -> Result<()> { let mut entries = Vec::with_capacity(LIMIT_COUNT); @@ -157,7 +157,7 @@ impl AsyncLog { if res_is_err || entries.len() <= 1 { break; } - Self::notify(&sender); + Self::notify(sender); let sleep_duration = if arc_background.load(Ordering::Relaxed) { diff --git a/asyncgit/src/status.rs b/asyncgit/src/status.rs index be37d35c..d7fc58b6 100644 --- a/asyncgit/src/status.rs +++ b/asyncgit/src/status.rs @@ -27,7 +27,7 @@ pub struct Status { } /// -#[derive(Default, Hash, Clone, PartialEq)] +#[derive(Default, Hash, Copy, Clone, PartialEq)] pub struct StatusParams { tick: u64, status_type: StatusType, @@ -83,7 +83,7 @@ impl AsyncStatus { /// pub fn fetch( &mut self, - params: StatusParams, + params: &StatusParams, ) -> Result> { if self.is_pending() { log::trace!("request blocked, still pending"); @@ -124,8 +124,8 @@ impl AsyncStatus { status_type, include_untracked, hash_request, - arc_current, - arc_last, + &arc_current, + &arc_last, ) .is_ok(); @@ -145,8 +145,8 @@ impl AsyncStatus { status_type: StatusType, include_untracked: bool, hash_request: u64, - arc_current: Arc>>, - arc_last: Arc>, + arc_current: &Arc>>, + arc_last: &Arc>, ) -> Result<()> { let res = Self::get_status(status_type, include_untracked)?; log::trace!( diff --git a/asyncgit/src/sync/branch/mod.rs b/asyncgit/src/sync/branch/mod.rs index c46318f4..edfd0730 100644 --- a/asyncgit/src/sync/branch/mod.rs +++ b/asyncgit/src/sync/branch/mod.rs @@ -81,7 +81,7 @@ pub struct BranchInfo { impl BranchInfo { /// returns details about local branch or None - pub fn local_details(&self) -> Option<&LocalBranch> { + pub const fn local_details(&self) -> Option<&LocalBranch> { if let BranchDetails::Local(details) = &self.details { return Some(details); } @@ -283,11 +283,10 @@ pub fn checkout_remote_branch( return Err(Error::UncommittedChanges); } - let name = if let Some(pos) = branch.name.rfind('/') { - branch.name[pos..].to_string() - } else { - branch.name.clone() - }; + let name = branch.name.rfind('/').map_or_else( + || branch.name.clone(), + |pos| branch.name[pos..].to_string(), + ); let commit = repo.find_commit(branch.top_commit.into())?; let mut new_branch = repo.branch(&name, &commit, false)?; diff --git a/asyncgit/src/sync/commit.rs b/asyncgit/src/sync/commit.rs index 40981cbb..ef4204ee 100644 --- a/asyncgit/src/sync/commit.rs +++ b/asyncgit/src/sync/commit.rs @@ -30,9 +30,10 @@ pub fn amend( Ok(CommitId::new(new_id)) } -/// Wrap Repository::signature to allow unknown user.name. +/// Wrap `Repository::signature` to allow unknown user.name. /// /// See . +#[allow(clippy::redundant_pub_crate)] pub(crate) fn signature_allow_undefined_name( repo: &Repository, ) -> std::result::Result, git2::Error> { diff --git a/asyncgit/src/sync/commit_details.rs b/asyncgit/src/sync/commit_details.rs index 104d5f62..81fb6158 100644 --- a/asyncgit/src/sync/commit_details.rs +++ b/asyncgit/src/sync/commit_details.rs @@ -16,7 +16,7 @@ pub struct CommitSignature { impl CommitSignature { /// convert from git2-rs `Signature` - pub fn from(s: Signature<'_>) -> Self { + pub fn from(s: &Signature<'_>) -> Self { Self { name: s.name().unwrap_or("").to_string(), email: s.email().unwrap_or("").to_string(), @@ -38,11 +38,10 @@ impl CommitMessage { /// pub fn from(s: &str) -> Self { let mut lines = s.lines(); - let subject = if let Some(subject) = lines.next() { - subject.to_string() - } else { - String::new() - }; + let subject = lines.next().map_or_else( + String::new, + std::string::ToString::to_string, + ); let body: Vec = lines.map(std::string::ToString::to_string).collect(); @@ -90,8 +89,8 @@ pub fn get_commit_details( let commit = repo.find_commit(id.into())?; - let author = CommitSignature::from(commit.author()); - let committer = CommitSignature::from(commit.committer()); + let author = CommitSignature::from(&commit.author()); + let committer = CommitSignature::from(&commit.committer()); let committer = if author == committer { None } else { diff --git a/asyncgit/src/sync/commit_files.rs b/asyncgit/src/sync/commit_files.rs index ae5532de..70c3afe3 100644 --- a/asyncgit/src/sync/commit_files.rs +++ b/asyncgit/src/sync/commit_files.rs @@ -38,7 +38,7 @@ pub fn get_commit_files( Ok(res) } -/// +#[allow(clippy::redundant_pub_crate)] pub(crate) fn get_commit_diff( repo: &Repository, id: CommitId, diff --git a/asyncgit/src/sync/commits_info.rs b/asyncgit/src/sync/commits_info.rs index 8891e938..f5d28d1c 100644 --- a/asyncgit/src/sync/commits_info.rs +++ b/asyncgit/src/sync/commits_info.rs @@ -11,13 +11,13 @@ use unicode_truncate::UnicodeTruncateStr; pub struct CommitId(Oid); impl CommitId { - /// create new CommitId - pub fn new(id: Oid) -> Self { + /// create new `CommitId` + pub const fn new(id: Oid) -> Self { Self(id) } /// - pub(crate) fn get_oid(self) -> Oid { + pub(crate) const fn get_oid(self) -> Oid { self.0 } @@ -79,11 +79,10 @@ pub fn get_commits_info( let res = commits .map(|c: Commit| { let message = get_message(&c, Some(message_length_limit)); - let author = if let Some(name) = c.author().name() { - String::from(name) - } else { - String::from("") - }; + let author = c.author().name().map_or_else( + || String::from(""), + String::from, + ); CommitInfo { message, author, @@ -104,11 +103,10 @@ pub fn get_message( let msg = String::from_utf8_lossy(c.message_bytes()); let msg = msg.trim(); - if let Some(limit) = message_length_limit { - msg.unicode_truncate(limit).0.to_string() - } else { - msg.to_string() - } + message_length_limit.map_or_else( + || msg.to_string(), + |limit| msg.unicode_truncate(limit).0.to_string(), + ) } #[cfg(test)] diff --git a/asyncgit/src/sync/cred.rs b/asyncgit/src/sync/cred.rs index 4d841d49..e5d87520 100644 --- a/asyncgit/src/sync/cred.rs +++ b/asyncgit/src/sync/cred.rs @@ -18,15 +18,15 @@ pub struct BasicAuthCredential { impl BasicAuthCredential { /// - pub fn is_complete(&self) -> bool { + pub const fn is_complete(&self) -> bool { self.username.is_some() && self.password.is_some() } /// - pub fn new( + pub const fn new( username: Option, password: Option, ) -> Self { - BasicAuthCredential { username, password } + Self { username, password } } } diff --git a/asyncgit/src/sync/diff.rs b/asyncgit/src/sync/diff.rs index 4f47d9b4..950de8ef 100644 --- a/asyncgit/src/sync/diff.rs +++ b/asyncgit/src/sync/diff.rs @@ -28,7 +28,7 @@ pub enum DiffLineType { impl Default for DiffLineType { fn default() -> Self { - DiffLineType::None + Self::None } } @@ -129,7 +129,7 @@ pub(crate) fn get_diff_raw<'a>( let diff = if stage { // diff against head - if let Ok(id) = get_head_repo(&repo) { + if let Ok(id) = get_head_repo(repo) { let parent = repo.find_commit(id.into())?; let tree = parent.tree()?; @@ -157,15 +157,14 @@ pub(crate) fn get_diff_raw<'a>( /// returns diff of a specific file either in `stage` or workdir pub fn get_diff( repo_path: &str, - //TODO: make &str - p: String, + p: &str, stage: bool, ) -> Result { scope_time!("get_diff"); let repo = utils::repo(repo_path)?; let work_dir = work_dir(&repo)?; - let diff = get_diff_raw(&repo, &p, stage, false, None)?; + let diff = get_diff_raw(&repo, p, stage, false, None)?; raw_diff_to_file_diff(&diff, work_dir) } @@ -374,9 +373,7 @@ mod tests { assert_eq!(get_statuses(repo_path), (1, 0)); - let diff = - get_diff(repo_path, "foo/bar.txt".to_string(), false) - .unwrap(); + let diff = get_diff(repo_path, "foo/bar.txt", false).unwrap(); assert_eq!(diff.hunks.len(), 1); assert_eq!(diff.hunks[0].lines[1].content, "test\n"); @@ -402,12 +399,9 @@ mod tests { assert_eq!(get_statuses(repo_path), (0, 1)); - let diff = get_diff( - repo_path, - String::from(file_path.to_str().unwrap()), - true, - ) - .unwrap(); + let diff = + get_diff(repo_path, file_path.to_str().unwrap(), true) + .unwrap(); assert_eq!(diff.hunks.len(), 1); } @@ -473,8 +467,7 @@ mod tests { assert_eq!(get_statuses(repo_path), (1, 1)); - let res = get_diff(repo_path, "bar.txt".to_string(), false) - .unwrap(); + let res = get_diff(repo_path, "bar.txt", false).unwrap(); assert_eq!(res.hunks.len(), 2) } @@ -495,7 +488,7 @@ mod tests { let diff = get_diff( sub_path.to_str().unwrap(), - String::from(file_path.to_str().unwrap()), + file_path.to_str().unwrap(), false, ) .unwrap(); @@ -519,12 +512,9 @@ mod tests { File::create(&root.join(file_path))? .write_all(b"\x00\x02")?; - let diff = get_diff( - repo_path, - String::from(file_path.to_str().unwrap()), - false, - ) - .unwrap(); + let diff = + get_diff(repo_path, file_path.to_str().unwrap(), false) + .unwrap(); dbg!(&diff); assert_eq!(diff.sizes, (1, 2)); @@ -543,12 +533,9 @@ mod tests { File::create(&root.join(file_path))? .write_all(b"\x00\xc7")?; - let diff = get_diff( - repo_path, - String::from(file_path.to_str().unwrap()), - false, - ) - .unwrap(); + let diff = + get_diff(repo_path, file_path.to_str().unwrap(), false) + .unwrap(); dbg!(&diff); assert_eq!(diff.sizes, (0, 2)); diff --git a/asyncgit/src/sync/hooks.rs b/asyncgit/src/sync/hooks.rs index a74e51f4..ac6d567a 100644 --- a/asyncgit/src/sync/hooks.rs +++ b/asyncgit/src/sync/hooks.rs @@ -4,7 +4,7 @@ use scopetime::scope_time; use std::{ fs::File, io::{Read, Write}, - path::{Path, PathBuf}, + path::Path, process::Command, }; @@ -13,7 +13,7 @@ const HOOK_PRE_COMMIT: &str = ".git/hooks/pre-commit"; const HOOK_COMMIT_MSG: &str = ".git/hooks/commit-msg"; const HOOK_COMMIT_MSG_TEMP_FILE: &str = ".git/COMMIT_EDITMSG"; -/// this hook is documented here https://git-scm.com/docs/githooks#_commit_msg +/// this hook is documented here /// we use the same convention as other git clients to create a temp file containing /// the commit message at `.git/COMMIT_EDITMSG` and pass it's relative path as the only /// parameter to the hook script. @@ -46,7 +46,7 @@ pub fn hooks_commit_msg( } } -/// this hook is documented here https://git-scm.com/docs/githooks#_pre_commit +/// this hook is documented here /// pub fn hooks_pre_commit(repo_path: &str) -> Result { scope_time!("hooks_pre_commit"); @@ -89,7 +89,7 @@ fn hook_runable(path: &str, hook: &str) -> bool { let path = Path::new(path); let path = path.join(hook); - path.exists() && is_executable(path) + path.exists() && is_executable(&path) } /// @@ -102,7 +102,7 @@ pub enum HookResult { } /// this function calls hook scripts based on conventions documented here -/// https://git-scm.com/docs/githooks +/// see fn run_hook( path: &str, hook_script: &str, @@ -135,7 +135,7 @@ fn run_hook( } #[cfg(not(windows))] -fn is_executable(path: PathBuf) -> bool { +fn is_executable(path: &Path) -> bool { use std::os::unix::fs::PermissionsExt; let metadata = match path.metadata() { Ok(metadata) => metadata, @@ -149,7 +149,7 @@ fn is_executable(path: PathBuf) -> bool { #[cfg(windows)] /// windows does not consider bash scripts to be executable so we consider everything /// to be executable (which is not far from the truth for windows platform.) -fn is_executable(_: PathBuf) -> bool { +const fn is_executable(_: &Path) -> bool { true } diff --git a/asyncgit/src/sync/hunks.rs b/asyncgit/src/sync/hunks.rs index cf347bb8..fd77d772 100644 --- a/asyncgit/src/sync/hunks.rs +++ b/asyncgit/src/sync/hunks.rs @@ -12,23 +12,21 @@ use scopetime::scope_time; /// pub fn stage_hunk( repo_path: &str, - file_path: String, + file_path: &str, hunk_hash: u64, ) -> Result<()> { scope_time!("stage_hunk"); let repo = repo(repo_path)?; - let diff = get_diff_raw(&repo, &file_path, false, false, None)?; + let diff = get_diff_raw(&repo, file_path, false, false, None)?; let mut opt = ApplyOptions::new(); opt.hunk_callback(|hunk| { - if let Some(hunk) = hunk { + hunk.map_or(false, |hunk| { let header = HunkHeader::from(hunk); hash(&header) == hunk_hash - } else { - false - } + }) }); repo.apply(&diff, ApplyLocation::Index, Some(&mut opt))?; @@ -39,14 +37,14 @@ pub fn stage_hunk( /// this will fail for an all untracked file pub fn reset_hunk( repo_path: &str, - file_path: String, + file_path: &str, hunk_hash: u64, ) -> Result<()> { scope_time!("reset_hunk"); let repo = repo(repo_path)?; - let diff = get_diff_raw(&repo, &file_path, false, false, None)?; + let diff = get_diff_raw(&repo, file_path, false, false, None)?; let hunk_index = find_hunk_index(&diff, hunk_hash); if let Some(hunk_index) = hunk_index { @@ -58,8 +56,7 @@ pub fn reset_hunk( res }); - let diff = - get_diff_raw(&repo, &file_path, false, true, None)?; + let diff = get_diff_raw(&repo, file_path, false, true, None)?; repo.apply(&diff, ApplyLocation::WorkDir, Some(&mut opt))?; @@ -98,14 +95,14 @@ fn find_hunk_index(diff: &Diff, hunk_hash: u64) -> Option { /// pub fn unstage_hunk( repo_path: &str, - file_path: String, + file_path: &str, hunk_hash: u64, ) -> Result { scope_time!("revert_hunk"); let repo = repo(repo_path)?; - let diff = get_diff_raw(&repo, &file_path, true, false, None)?; + let diff = get_diff_raw(&repo, file_path, true, false, None)?; let diff_count_positive = diff.deltas().len(); let hunk_index = find_hunk_index(&diff, hunk_hash); @@ -114,7 +111,7 @@ pub fn unstage_hunk( Ok, )?; - let diff = get_diff_raw(&repo, &file_path, true, true, None)?; + let diff = get_diff_raw(&repo, file_path, true, true, None)?; if diff.deltas().len() != diff_count_positive { return Err(Error::Generic(format!( @@ -174,13 +171,13 @@ mod tests { let diff = get_diff( sub_path.to_str().unwrap(), - String::from(file_path.to_str().unwrap()), + file_path.to_str().unwrap(), false, )?; assert!(reset_hunk( repo_path, - String::from(file_path.to_str().unwrap()), + file_path.to_str().unwrap(), diff.hunks[0].header_hash, ) .is_err()); diff --git a/asyncgit/src/sync/logwalker.rs b/asyncgit/src/sync/logwalker.rs index 2b785cc4..22ae7865 100644 --- a/asyncgit/src/sync/logwalker.rs +++ b/asyncgit/src/sync/logwalker.rs @@ -10,7 +10,7 @@ pub struct LogWalker<'a> { impl<'a> LogWalker<'a> { /// - pub fn new(repo: &'a Repository) -> Self { + pub const fn new(repo: &'a Repository) -> Self { Self { repo, revwalk: None, diff --git a/asyncgit/src/sync/patches.rs b/asyncgit/src/sync/patches.rs index b9333aa5..8d3db37b 100644 --- a/asyncgit/src/sync/patches.rs +++ b/asyncgit/src/sync/patches.rs @@ -2,21 +2,20 @@ use super::diff::{get_diff_raw, HunkHeader}; use crate::error::{Error, Result}; use git2::{Diff, DiffLine, Patch, Repository}; -// +#[allow(clippy::redundant_pub_crate)] pub(crate) struct HunkLines<'a> { pub hunk: HunkHeader, pub lines: Vec>, } -/// +#[allow(clippy::redundant_pub_crate)] pub(crate) fn get_file_diff_patch_and_hunklines<'a>( repo: &'a Repository, file: &str, is_staged: bool, reverse: bool, ) -> Result<(Patch<'a>, Vec>)> { - let diff = - get_diff_raw(&repo, file, is_staged, reverse, Some(1))?; + let diff = get_diff_raw(repo, file, is_staged, reverse, Some(1))?; let patches = get_patches(&diff)?; if patches.len() > 1 { return Err(Error::Generic(String::from("patch error"))); @@ -64,7 +63,7 @@ fn get_patches<'a>(diff: &Diff<'a>) -> Result>> { let mut res = Vec::with_capacity(count); for idx in 0..count { - let p = Patch::from_diff(&diff, idx)?; + let p = Patch::from_diff(diff, idx)?; if let Some(p) = p { res.push(p); } diff --git a/asyncgit/src/sync/remotes/push.rs b/asyncgit/src/sync/remotes/push.rs index dc8d85f9..0f7887a0 100644 --- a/asyncgit/src/sync/remotes/push.rs +++ b/asyncgit/src/sync/remotes/push.rs @@ -24,7 +24,7 @@ pub trait AsyncProgress: Clone + Send + Sync { /// #[derive(Debug, Clone, PartialEq)] -pub(crate) enum ProgressNotification { +pub enum ProgressNotification { /// UpdateTips { /// @@ -65,11 +65,11 @@ pub(crate) enum ProgressNotification { impl AsyncProgress for ProgressNotification { fn is_done(&self) -> bool { - *self == ProgressNotification::Done + *self == Self::Done } fn progress(&self) -> ProgressPercent { match *self { - ProgressNotification::Packing { + Self::Packing { stage, current, total, @@ -79,12 +79,10 @@ impl AsyncProgress for ProgressNotification { ProgressPercent::new(current, total) } }, - ProgressNotification::PushTransfer { - current, - total, - .. - } => ProgressPercent::new(current, total), - ProgressNotification::Transfer { + Self::PushTransfer { current, total, .. } => { + ProgressPercent::new(current, total) + } + Self::Transfer { objects, total_objects, .. @@ -94,7 +92,7 @@ impl AsyncProgress for ProgressNotification { } } -/// +#[allow(clippy::redundant_pub_crate)] pub(crate) fn push( repo_path: &str, remote: &str, @@ -130,6 +128,7 @@ pub(crate) fn push( Ok(()) } +#[allow(clippy::redundant_pub_crate)] pub(crate) fn remote_callbacks<'a>( sender: Option>, basic_credential: Option, @@ -226,7 +225,7 @@ pub(crate) fn remote_callbacks<'a>( username: Some(user), password: Some(pwd), }) if allowed_types.is_user_pass_plaintext() => { - Cred::userpass_plaintext(&user, &pwd) + Cred::userpass_plaintext(user, pwd) } Some(BasicAuthCredential { username: Some(user), diff --git a/asyncgit/src/sync/remotes/tags.rs b/asyncgit/src/sync/remotes/tags.rs index 155bf04f..52deb1e7 100644 --- a/asyncgit/src/sync/remotes/tags.rs +++ b/asyncgit/src/sync/remotes/tags.rs @@ -32,15 +32,15 @@ pub enum PushTagsProgress { impl AsyncProgress for PushTagsProgress { fn progress(&self) -> ProgressPercent { match self { - PushTagsProgress::CheckRemote => ProgressPercent::empty(), - PushTagsProgress::Push { pushed, total } => { + Self::CheckRemote => ProgressPercent::empty(), + Self::Push { pushed, total } => { ProgressPercent::new(*pushed, *total) } - PushTagsProgress::Done => ProgressPercent::full(), + Self::Done => ProgressPercent::full(), } } fn is_done(&self) -> bool { - *self == PushTagsProgress::Done + *self == Self::Done } } @@ -98,7 +98,7 @@ fn tags_missing_remote( } /// -pub(crate) fn push_tags( +pub fn push_tags( repo_path: &str, remote: &str, basic_credential: Option, @@ -142,9 +142,9 @@ pub(crate) fn push_tags( }); } - progress_sender - .as_ref() - .map(|sender| sender.send(PushTagsProgress::Done)); + drop(basic_credential); + + progress_sender.map(|sender| sender.send(PushTagsProgress::Done)); Ok(()) } diff --git a/asyncgit/src/sync/staging/discard_tracked.rs b/asyncgit/src/sync/staging/discard_tracked.rs index 270cc63b..4adda5b5 100644 --- a/asyncgit/src/sync/staging/discard_tracked.rs +++ b/asyncgit/src/sync/staging/discard_tracked.rs @@ -32,7 +32,7 @@ pub fn discard_lines( let working_content = load_file(&repo, file_path)?; let old_lines = working_content.lines().collect::>(); - apply_selection(lines, &hunks, old_lines, false, true)? + apply_selection(lines, &hunks, &old_lines, false, true)? }; repo_write_file(&repo, file_path, new_content.as_str())?; diff --git a/asyncgit/src/sync/staging/mod.rs b/asyncgit/src/sync/staging/mod.rs index 355685fa..ede98ec5 100644 --- a/asyncgit/src/sync/staging/mod.rs +++ b/asyncgit/src/sync/staging/mod.rs @@ -71,10 +71,11 @@ impl NewFromOldContent { } // this is the heart of the per line discard,stage,unstage. heavily inspired by the great work in nodegit: https://github.com/nodegit/nodegit +#[allow(clippy::redundant_pub_crate)] pub(crate) fn apply_selection( lines: &[DiffLinePosition], hunks: &[HunkLines], - old_lines: Vec<&str>, + old_lines: &[&str], is_staged: bool, reverse: bool, ) -> Result { @@ -103,7 +104,7 @@ pub(crate) fn apply_selection( } if first_hunk_encountered { - new_content.catchup_to_hunkstart(hunk_start, &old_lines); + new_content.catchup_to_hunkstart(hunk_start, old_lines); for hunk_line in &hunk.lines { let hunk_line_pos: DiffLinePosition = @@ -140,7 +141,7 @@ pub(crate) fn apply_selection( new_content.skip_old_line(); } } else { - new_content.add_old_line(&old_lines); + new_content.add_old_line(old_lines); } } else { if hunk_line.origin() != char_added { @@ -159,10 +160,10 @@ pub(crate) fn apply_selection( } } - Ok(new_content.finish(&old_lines)) + Ok(new_content.finish(old_lines)) } -pub(crate) fn load_file( +pub fn load_file( repo: &Repository, file_path: &str, ) -> Result { diff --git a/asyncgit/src/sync/staging/stage_tracked.rs b/asyncgit/src/sync/staging/stage_tracked.rs index d1d4d8dd..c541ad46 100644 --- a/asyncgit/src/sync/staging/stage_tracked.rs +++ b/asyncgit/src/sync/staging/stage_tracked.rs @@ -43,7 +43,7 @@ pub fn stage_lines( let old_lines = indexed_content.lines().collect::>(); - apply_selection(lines, &hunks, old_lines, is_stage, false)? + apply_selection(lines, &hunks, &old_lines, is_stage, false)? }; let blob_id = repo.blob(new_content.as_bytes())?; @@ -97,8 +97,7 @@ mod test { ) .unwrap(); - let diff = - get_diff(path, String::from("test.txt"), true).unwrap(); + let diff = get_diff(path, "test.txt", true).unwrap(); assert_eq!(diff.lines, 3); assert_eq!( @@ -140,8 +139,7 @@ c = 4"; ) .unwrap(); - let diff = - get_diff(path, String::from("test.txt"), true).unwrap(); + let diff = get_diff(path, "test.txt", true).unwrap(); assert_eq!(diff.lines, 5); assert_eq!( @@ -174,8 +172,7 @@ c = 4"; assert_eq!(get_statuses(path), (0, 1)); - let diff_before = - get_diff(path, String::from("test.txt"), true).unwrap(); + let diff_before = get_diff(path, "test.txt", true).unwrap(); assert_eq!(diff_before.lines, 5); @@ -192,8 +189,7 @@ c = 4"; assert_eq!(get_statuses(path), (1, 1)); - let diff = - get_diff(path, String::from("test.txt"), true).unwrap(); + let diff = get_diff(path, "test.txt", true).unwrap(); assert_eq!(diff.lines, 4); } diff --git a/asyncgit/src/sync/stash.rs b/asyncgit/src/sync/stash.rs index a975a709..ff5999e6 100644 --- a/asyncgit/src/sync/stash.rs +++ b/asyncgit/src/sync/stash.rs @@ -28,7 +28,7 @@ pub fn is_stash_commit( id: &CommitId, ) -> Result { let stashes = get_stashes(repo_path)?; - Ok(stashes.contains(&id)) + Ok(stashes.contains(id)) } /// diff --git a/asyncgit/src/sync/state.rs b/asyncgit/src/sync/state.rs index e51bef83..947528f2 100644 --- a/asyncgit/src/sync/state.rs +++ b/asyncgit/src/sync/state.rs @@ -16,9 +16,9 @@ pub enum RepoState { impl From for RepoState { fn from(state: RepositoryState) -> Self { match state { - RepositoryState::Clean => RepoState::Clean, - RepositoryState::Merge => RepoState::Merge, - _ => RepoState::Other, + RepositoryState::Clean => Self::Clean, + RepositoryState::Merge => Self::Merge, + _ => Self::Other, } } } diff --git a/asyncgit/src/sync/status.rs b/asyncgit/src/sync/status.rs index b2318552..3e58c3c3 100644 --- a/asyncgit/src/sync/status.rs +++ b/asyncgit/src/sync/status.rs @@ -43,11 +43,11 @@ impl From for StatusItemType { impl From for StatusItemType { fn from(d: Delta) -> Self { match d { - Delta::Added => StatusItemType::New, - Delta::Deleted => StatusItemType::Deleted, - Delta::Renamed => StatusItemType::Renamed, - Delta::Typechange => StatusItemType::Typechange, - _ => StatusItemType::Modified, + Delta::Added => Self::New, + Delta::Deleted => Self::Deleted, + Delta::Renamed => Self::Renamed, + Delta::Typechange => Self::Typechange, + _ => Self::Modified, } } } @@ -74,16 +74,16 @@ pub enum StatusType { impl Default for StatusType { fn default() -> Self { - StatusType::WorkingDir + Self::WorkingDir } } impl From for StatusShow { fn from(s: StatusType) -> Self { match s { - StatusType::WorkingDir => StatusShow::Workdir, - StatusType::Stage => StatusShow::Index, - StatusType::Both => StatusShow::IndexAndWorkdir, + StatusType::WorkingDir => Self::Workdir, + StatusType::Stage => Self::Index, + StatusType::Both => Self::IndexAndWorkdir, } } } diff --git a/asyncgit/src/sync/utils.rs b/asyncgit/src/sync/utils.rs index 70266afa..c98f9838 100644 --- a/asyncgit/src/sync/utils.rs +++ b/asyncgit/src/sync/utils.rs @@ -53,17 +53,16 @@ pub(crate) fn repo(repo_path: &str) -> Result { /// pub(crate) fn work_dir(repo: &Repository) -> Result<&Path> { - repo.workdir().map_or(Err(Error::NoWorkDir), |dir| Ok(dir)) + repo.workdir().ok_or(Error::NoWorkDir) } /// pub fn repo_work_dir(repo_path: &str) -> Result { let repo = repo(repo_path)?; - if let Some(workdir) = work_dir(&repo)?.to_str() { - Ok(workdir.to_string()) - } else { - Err(Error::Generic("invalid workdir".to_string())) - } + work_dir(&repo)?.to_str().map_or_else( + || Err(Error::Generic("invalid workdir".to_string())), + |workdir| Ok(workdir.to_string()), + ) } /// @@ -95,11 +94,7 @@ pub fn get_head_repo(repo: &Repository) -> Result { let head = repo.head()?.target(); - if let Some(head_id) = head { - Ok(head_id.into()) - } else { - Err(Error::NoHead) - } + head.map_or(Err(Error::NoHead), |head_id| Ok(head_id.into())) } /// add a file diff from workingdir to stage (will not add removed files see `stage_addremoved`) diff --git a/asyncgit/src/tags.rs b/asyncgit/src/tags.rs index f17ff686..388a60b4 100644 --- a/asyncgit/src/tags.rs +++ b/asyncgit/src/tags.rs @@ -55,8 +55,7 @@ impl AsyncTags { Ok(last .as_ref() - .map(|(last_time, _)| last_time.elapsed() > dur) - .unwrap_or(true)) + .map_or(true, |(last_time, _)| last_time.elapsed() > dur)) } /// @@ -78,8 +77,8 @@ impl AsyncTags { self.pending.fetch_add(1, Ordering::Relaxed); rayon_core::spawn(move || { - let notify = AsyncTags::getter(arc_last) - .expect("error getting tags"); + let notify = + Self::getter(&arc_last).expect("error getting tags"); arc_pending.fetch_sub(1, Ordering::Relaxed); @@ -96,13 +95,13 @@ impl AsyncTags { } fn getter( - arc_last: Arc>>, + arc_last: &Arc>>, ) -> Result { let tags = sync::get_tags(CWD)?; let hash = hash(&tags); - if Self::last_hash(arc_last.clone()) + if Self::last_hash(arc_last) .map(|last| last == hash) .unwrap_or_default() { @@ -119,7 +118,7 @@ impl AsyncTags { } fn last_hash( - last: Arc>>, + last: &Arc>>, ) -> Option { last.lock() .ok() diff --git a/src/app.rs b/src/app.rs index 77184554..ff786a17 100644 --- a/src/app.rs +++ b/src/app.rs @@ -500,7 +500,7 @@ impl App { } } Action::ResetHunk(path, hash) => { - sync::reset_hunk(CWD, path, hash)?; + sync::reset_hunk(CWD, &path, hash)?; flags.insert(NeedsUpdate::ALL); } Action::ResetLines(path, lines) => { diff --git a/src/components/diff.rs b/src/components/diff.rs index 373f0f60..9eb5ecf1 100644 --- a/src/components/diff.rs +++ b/src/components/diff.rs @@ -469,11 +469,7 @@ impl DiffComponent { if let Some(diff) = &self.diff { if let Some(hunk) = self.selected_hunk { let hash = diff.hunks[hunk].header_hash; - sync::unstage_hunk( - CWD, - self.current.path.clone(), - hash, - )?; + sync::unstage_hunk(CWD, &self.current.path, hash)?; self.queue_update(); } } @@ -484,12 +480,14 @@ impl DiffComponent { fn stage_hunk(&mut self) -> Result<()> { if let Some(diff) = &self.diff { if let Some(hunk) = self.selected_hunk { - let path = self.current.path.clone(); if diff.untracked { - sync::stage_add_file(CWD, Path::new(&path))?; + sync::stage_add_file( + CWD, + Path::new(&self.current.path), + )?; } else { let hash = diff.hunks[hunk].header_hash; - sync::stage_hunk(CWD, path, hash)?; + sync::stage_hunk(CWD, &self.current.path, hash)?; } self.queue_update(); diff --git a/src/tabs/stashing.rs b/src/tabs/stashing.rs index a4d26947..e0098a01 100644 --- a/src/tabs/stashing.rs +++ b/src/tabs/stashing.rs @@ -73,7 +73,7 @@ impl Stashing { /// pub fn update(&mut self) -> Result<()> { if self.visible { - self.git_status.fetch(StatusParams::new( + self.git_status.fetch(&StatusParams::new( StatusType::Both, self.options.stash_untracked, ))?; diff --git a/src/tabs/status.rs b/src/tabs/status.rs index bc3477a3..3836daef 100644 --- a/src/tabs/status.rs +++ b/src/tabs/status.rs @@ -304,12 +304,12 @@ impl Status { if self.is_visible() { self.git_diff.refresh()?; - self.git_status_workdir.fetch(StatusParams::new( + self.git_status_workdir.fetch(&StatusParams::new( StatusType::WorkingDir, true, ))?; self.git_status_stage - .fetch(StatusParams::new(StatusType::Stage, true))?; + .fetch(&StatusParams::new(StatusType::Stage, true))?; self.branch_compare(); }