use std::collections::HashMap;
use std::sync::Arc;
use crate::config::ConfigSet;
use crate::diff::core::diff_trees_for_pathspecs;
use crate::diff::posix_ere::PosixEre;
use crate::diff::structured::SideBytes;
use crate::diff::{
detect_renames_with_policy, renames_from_config, DetectRenamesOptions, DiffEntry, DiffStatus,
RenameDetection,
};
use crate::error::{Error, Result};
use crate::objects::{parse_commit, FileMode, ObjectId};
use crate::parallel::ThreadPolicy;
use crate::repo::Repository;
#[derive(Debug, Clone, Copy)]
pub(crate) struct PickaxeRenames<'a> {
threshold: Option<u32>,
config: &'a ConfigSet,
}
impl<'a> PickaxeRenames<'a> {
pub fn new(detection: RenameDetection, config: &'a ConfigSet) -> Self {
Self {
threshold: detection.threshold_percent(),
config,
}
}
pub fn from_config(config: &'a ConfigSet) -> Self {
Self::new(renames_from_config(config), config)
}
pub fn config(&self) -> &'a ConfigSet {
self.config
}
}
#[derive(Debug, Clone)]
pub enum PickaxeKind {
Occurrences {
needle: String,
},
LineGrep,
}
#[derive(Debug, Clone)]
pub struct Pickaxe {
kind: PickaxeKind,
ignore_case: bool,
pickaxe_regex: bool,
ere: Option<PosixEre>,
}
impl Pickaxe {
#[must_use]
pub fn occurrences(needle: impl Into<String>) -> Self {
Self {
kind: PickaxeKind::Occurrences {
needle: needle.into(),
},
ignore_case: false,
pickaxe_regex: false,
ere: None,
}
}
pub fn line_grep(pattern: &str, ignore_case: bool) -> std::result::Result<Self, PickaxeError> {
let ere = compile_pickaxe_ere(pattern, ignore_case)?;
Ok(Self {
kind: PickaxeKind::LineGrep,
ignore_case,
pickaxe_regex: false,
ere: Some(ere),
})
}
#[must_use]
pub fn ignore_case(mut self, on: bool) -> Self {
self.ignore_case = on;
self
}
#[must_use]
pub fn pickaxe_regex(mut self, on: bool) -> Self {
self.pickaxe_regex = on;
self
}
pub fn build(mut self) -> std::result::Result<Self, PickaxeError> {
if self.pickaxe_regex {
let PickaxeKind::Occurrences { ref needle } = self.kind else {
return Err(PickaxeError::InvalidPattern {
pattern: String::new(),
detail: "--pickaxe-regex cannot be used with -G".into(),
});
};
self.ere = Some(compile_pickaxe_ere(needle, self.ignore_case)?);
}
Ok(self)
}
#[must_use]
pub fn is_active(&self) -> bool {
true
}
#[must_use]
pub fn into_shared(self) -> Arc<Self> {
Arc::new(self)
}
pub fn matches_commit(
&self,
repo: &Repository,
commit_oid: ObjectId,
paths: &[String],
renames: RenameDetection,
) -> Result<bool> {
let config = repo.config().snapshot()?;
let data = repo.odb().read(&commit_oid)?.data;
let commit = parse_commit(&data)?;
let parent_ctx = crate::shallow::EffectiveCommitParents::load(repo);
let effective_parents = parent_ctx.for_commit(commit_oid, &commit.parents);
if effective_parents.len() > 1 {
return Ok(false);
}
let parent_tree = if let Some(&parent_oid) = effective_parents.first() {
let parent_data = repo.odb().read(&parent_oid)?.data;
let parent = parse_commit(&parent_data)?;
if parent.tree == commit.tree {
return Ok(false);
}
Some(parent.tree)
} else {
None
};
let renames = PickaxeRenames::new(renames, config.as_ref());
self.matches_trees(
repo,
parent_tree.as_ref(),
&commit.tree,
paths,
renames,
&mut HashMap::new(),
)
}
pub(crate) fn matches_trees(
&self,
repo: &Repository,
parent_tree: Option<&ObjectId>,
commit_tree: &ObjectId,
paths: &[String],
renames: PickaxeRenames<'_>,
blob_occurrence_cache: &mut HashMap<ObjectId, usize>,
) -> Result<bool> {
let diff_options = crate::diff::DiffOptions::from_config(renames.config());
let odb = repo.odb();
let pathspec_matcher = if paths.is_empty() {
None
} else {
Some(repo.pathspec_matcher(paths)?)
};
let entries = diff_trees_for_pathspecs(
odb,
parent_tree,
Some(commit_tree),
paths,
pathspec_matcher.as_ref(),
)?;
let mut unpaired = Vec::new();
for entry in entries {
if matches!(entry.status, DiffStatus::Added | DiffStatus::Deleted) {
unpaired.push(entry);
} else if self.changed_filepair_matches(
odb,
&entry,
&diff_options,
blob_occurrence_cache,
)? {
return Ok(true);
}
}
if unpaired.is_empty() {
return Ok(false);
}
let mut any_side_matches = false;
for entry in &unpaired {
if self.side_may_match(odb, entry, blob_occurrence_cache)? {
any_side_matches = true;
break;
}
}
if !any_side_matches {
return Ok(false);
}
let pairs = match renames.threshold {
Some(threshold) => {
detect_renames_with_policy(
odb,
None,
unpaired,
threshold,
renames.config,
&ThreadPolicy::default(),
None,
DetectRenamesOptions::default(),
)?
.entries
}
None => unpaired,
};
for entry in &pairs {
if self.changed_filepair_matches(odb, entry, &diff_options, blob_occurrence_cache)? {
return Ok(true);
}
}
Ok(false)
}
fn changed_filepair_matches(
&self,
odb: &crate::odb::Odb,
entry: &DiffEntry,
diff_options: &crate::diff::DiffOptions,
blob_occurrence_cache: &mut HashMap<ObjectId, usize>,
) -> Result<bool> {
if entry.old_oid == entry.new_oid && entry.old_mode == entry.new_mode {
return Ok(false);
}
self.filepair_matches(odb, entry, diff_options, blob_occurrence_cache)
}
fn side_may_match(
&self,
odb: &crate::odb::Odb,
entry: &DiffEntry,
blob_occurrence_cache: &mut HashMap<ObjectId, usize>,
) -> Result<bool> {
let (oid, mode) = if entry.status == DiffStatus::Deleted {
(&entry.old_oid, entry.old_mode)
} else {
(&entry.new_oid, entry.new_mode)
};
match &self.kind {
PickaxeKind::Occurrences { .. } => {
Ok(self.occurrences_in(odb, oid, mode, blob_occurrence_cache)? > 0)
}
PickaxeKind::LineGrep => {
let (bytes, binary) = blob_side(odb, mode, oid)?;
let Some(regex) = self.ere.as_ref().filter(|_| !binary) else {
return Ok(false);
};
Ok(regex.is_match(&bytes.data))
}
}
}
fn filepair_matches(
&self,
odb: &crate::odb::Odb,
entry: &DiffEntry,
diff_options: &crate::diff::DiffOptions,
blob_occurrence_cache: &mut HashMap<ObjectId, usize>,
) -> Result<bool> {
match &self.kind {
PickaxeKind::Occurrences { .. } => {
let old = self.occurrences_in(
odb,
&entry.old_oid,
entry.old_mode,
blob_occurrence_cache,
)?;
let new = self.occurrences_in(
odb,
&entry.new_oid,
entry.new_mode,
blob_occurrence_cache,
)?;
Ok(old != new)
}
PickaxeKind::LineGrep => {
let (old_bytes, old_bin) = blob_side(odb, entry.old_mode, &entry.old_oid)?;
let (new_bytes, new_bin) = blob_side(odb, entry.new_mode, &entry.new_oid)?;
if old_bin || new_bin {
return Ok(false);
}
let Some(regex) = self.ere.as_ref() else {
return Ok(false);
};
if !regex.is_match(&old_bytes.data) && !regex.is_match(&new_bytes.data) {
return Ok(false);
}
Ok(line_grep_match(
&String::from_utf8_lossy(&old_bytes.data),
&String::from_utf8_lossy(&new_bytes.data),
regex,
diff_options,
))
}
}
}
fn occurrences_in(
&self,
odb: &crate::odb::Odb,
oid: &ObjectId,
mode: FileMode,
cache: &mut HashMap<ObjectId, usize>,
) -> Result<usize> {
let PickaxeKind::Occurrences { needle } = &self.kind else {
return Ok(0);
};
if mode.is_absent() || *oid == ObjectId::zero() {
return Ok(0);
}
let count_in =
|bytes: &[u8]| count_occurrences(bytes, needle, self.ignore_case, self.ere.as_ref());
if mode == FileMode::GITLINK {
let (bytes, _) = blob_side(odb, mode, oid)?;
return Ok(count_in(bytes.data.as_slice()));
}
if let Some(&count) = cache.get(oid) {
return Ok(count);
}
let count = count_in(&odb.read(oid)?.data);
cache.insert(*oid, count);
Ok(count)
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum PickaxeError {
#[error("invalid pickaxe pattern `{pattern}`: {detail}")]
InvalidPattern {
pattern: String,
detail: String,
},
}
impl From<PickaxeError> for Error {
fn from(value: PickaxeError) -> Self {
Error::Diff(crate::error::DiffError::Pickaxe(value))
}
}
fn compile_pickaxe_ere(
pattern: &str,
ignore_case: bool,
) -> std::result::Result<PosixEre, PickaxeError> {
PosixEre::compile(pattern, ignore_case).map_err(|detail| PickaxeError::InvalidPattern {
pattern: pattern.to_owned(),
detail,
})
}
fn count_occurrences(
haystack: &[u8],
needle: &str,
ignore_case: bool,
ere: Option<&PosixEre>,
) -> usize {
if haystack.is_empty() {
return 0;
}
if let Some(re) = ere {
return re.count_nonoverlapping(haystack);
}
if ignore_case {
let h = String::from_utf8_lossy(haystack).to_lowercase();
let n = needle.to_lowercase();
return count_substr(h.as_bytes(), n.as_bytes());
}
count_substr(haystack, needle.as_bytes())
}
fn count_substr(haystack: &[u8], needle: &[u8]) -> usize {
if needle.is_empty() {
return 0;
}
memchr::memmem::find_iter(haystack, needle).count()
}
fn blob_side(odb: &crate::odb::Odb, mode: FileMode, oid: &ObjectId) -> Result<(SideBytes, bool)> {
if mode == FileMode::GITLINK {
let line = if *oid == ObjectId::zero() {
String::new()
} else {
format!("Subproject commit {}\n", oid.to_hex())
};
return Ok((SideBytes::from_bytes(line.into_bytes()), false));
}
if mode.is_absent() || *oid == ObjectId::zero() {
return Ok((SideBytes::from_bytes(Vec::new()), false));
}
let data = odb.read(oid)?.data;
let binary = data.iter().take(8000).any(|&b| b == 0);
Ok((SideBytes::from_bytes(data), binary))
}
fn line_grep_match(
old_text: &str,
new_text: &str,
regex: &PosixEre,
diff_options: &crate::diff::DiffOptions,
) -> bool {
use crate::diff::core::compacted_line_ops_for_options;
use crate::diff::unified_emit::LineSide;
use similar::DiffOp;
let before = LineSide::from_text(old_text);
let after = LineSide::from_text(new_text);
let old_lines: Vec<&str> = before.lines().map(|l| l.body).collect();
let new_lines: Vec<&str> = after.lines().map(|l| l.body).collect();
for op in compacted_line_ops_for_options(old_text, new_text, diff_options) {
match op {
DiffOp::Equal { .. } => {}
DiffOp::Delete {
old_index, old_len, ..
} => {
for line in &old_lines[old_index..old_index + old_len] {
if regex.is_match(line.as_bytes()) {
return true;
}
}
}
DiffOp::Insert {
new_index, new_len, ..
} => {
for line in &new_lines[new_index..new_index + new_len] {
if regex.is_match(line.as_bytes()) {
return true;
}
}
}
DiffOp::Replace {
old_index,
old_len,
new_index,
new_len,
..
} => {
for line in &old_lines[old_index..old_index + old_len] {
if regex.is_match(line.as_bytes()) {
return true;
}
}
for line in &new_lines[new_index..new_index + new_len] {
if regex.is_match(line.as_bytes()) {
return true;
}
}
}
}
}
false
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn literal_counts_do_not_overlap() {
assert_eq!(count_occurrences(b"aaaa", "aa", false, None), 2);
assert_eq!(count_occurrences(b"aaa", "aa", false, None), 1);
assert_eq!(count_occurrences(b"abcabc", "abc", false, None), 2);
assert_eq!(count_occurrences(b"abc", "", false, None), 0);
assert_eq!(count_occurrences(b"", "a", false, None), 0);
}
#[test]
fn ignore_case_counts_fold_both_sides() {
assert_eq!(count_occurrences(b"Needle NEEDLE", "needle", true, None), 2);
assert_eq!(
count_occurrences(b"Needle NEEDLE", "needle", false, None),
0
);
}
}