From db448d21a53d9f1ac7c8c03b3bb679f9d6371a72 Mon Sep 17 00:00:00 2001 From: Sahib Yar Date: Sun, 29 Nov 2026 18:36:29 +0500 Subject: [PATCH 1/4] fix: apply the git recency boost to file priority The recency boost never changed file priority or output order. Three defects each disabled it on its own: - serialize_repo computed the boost map but process_files_parallel ignored it (`_boost_map`), and the processor was built with empty commit_times. The processor now takes the boost map, keyed by canonical absolute path so subdirectory inputs match the repo-root paths git reports. - get_recent_commit_times_git2 walked the full tree of each commit, so every file in HEAD got HEAD's time and all boosts were 0. Each commit is now diffed against its first parent, so a file only gets the time of a commit that changed it. - clap-config-file ignores default_value on config-only scalars, so max_git_depth was 0 on the CLI and no commits were scanned. It now falls back to DEFAULT_MAX_GIT_DEPTH (100) unless the config sets it. Fixes #272 --- src/config.rs | 73 ++++++++++++++++++++- src/defaults.rs | 3 + src/lib.rs | 51 +++++++++------ src/parallel.rs | 63 +++++++++++++----- src/priority.rs | 49 ++++++++++---- tests/git_boost_test.rs | 139 ++++++++++++++++++++++++++++++++++++++++ tests/priority_test.rs | 35 ++++++++++ 7 files changed, 364 insertions(+), 49 deletions(-) create mode 100644 tests/git_boost_test.rs diff --git a/src/config.rs b/src/config.rs index 1287b813..15b63a1e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -6,7 +6,10 @@ use std::io::{self, BufRead, BufReader, IsTerminal}; use std::{fs, path::Path, process::Command, str::FromStr, time::UNIX_EPOCH}; use crate::{ - defaults::{BINARY_FILE_EXTENSIONS, DEFAULT_IGNORE_PATTERNS, DEFAULT_OUTPUT_TEMPLATE}, + defaults::{ + BINARY_FILE_EXTENSIONS, DEFAULT_IGNORE_PATTERNS, DEFAULT_MAX_GIT_DEPTH, + DEFAULT_OUTPUT_TEMPLATE, + }, priority::PriorityRule, }; @@ -143,7 +146,7 @@ impl Default for YekConfig { stream: false, token_mode: false, output_file_full_path: None, - max_git_depth: 100, + max_git_depth: DEFAULT_MAX_GIT_DEPTH, } } } @@ -207,6 +210,7 @@ impl YekConfig { let (mut cfg, config_path, _config_format) = YekConfig::parse_info(); cfg.apply_config_bool_overrides(config_path.as_deref()); + cfg.apply_config_scalar_defaults(config_path.as_deref()); // Handle version flag if cfg.version { @@ -326,6 +330,31 @@ impl YekConfig { self.tree_only |= config_bool(&settings, "tree_only", "tree-only"); } + /// clap-config-file ignores `default_value` on config-only scalar fields and + /// falls back to `Default::default()` (0). For `max_git_depth` that means + /// reading zero commits, which silently disables the Git recency boost. + /// Restore the documented default unless the config file sets a value. + fn apply_config_scalar_defaults(&mut self, config_path: Option<&Path>) { + let configured_depth = config_path + .and_then(|path| { + ::config::Config::builder() + .add_source(::config::File::from(path).required(false)) + .build() + .ok() + }) + .and_then(|settings| { + settings + .get_int("max_git_depth") + .or_else(|_| settings.get_int("max-git-depth")) + .ok() + }); + + self.max_git_depth = match configured_depth { + Some(depth) => i32::try_from(depth).unwrap_or(i32::MAX), + None => DEFAULT_MAX_GIT_DEPTH, + }; + } + /// Compute a quick checksum for the input paths (files and directories). /// For directories, it uses the top-level listing. For files, it uses the file metadata. pub fn get_checksum(input_paths: &[String]) -> String { @@ -739,3 +768,43 @@ mod bool_config_tests { assert!(!cfg.json && !cfg.debug && !cfg.line_numbers && !cfg.tree_header && !cfg.tree_only); } } + +#[cfg(test)] +mod scalar_default_tests { + use super::*; + + fn depth_after_defaults(config_path: Option<&Path>) -> i32 { + let mut cfg = YekConfig { + max_git_depth: 0, // what clap-config-file yields when the key is absent + ..YekConfig::default() + }; + cfg.apply_config_scalar_defaults(config_path); + cfg.max_git_depth + } + + #[test] + fn max_git_depth_defaults_to_100_without_a_config_file() { + assert_eq!(depth_after_defaults(None), DEFAULT_MAX_GIT_DEPTH); + } + + #[test] + fn max_git_depth_defaults_to_100_when_config_omits_it() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("yek.yaml"); + fs::write(&path, "json: false\n").unwrap(); + + assert_eq!(depth_after_defaults(Some(&path)), DEFAULT_MAX_GIT_DEPTH); + } + + #[test] + fn max_git_depth_from_config_is_respected_in_either_key_style() { + let dir = tempfile::tempdir().unwrap(); + let snake = dir.path().join("snake.yaml"); + let kebab = dir.path().join("kebab.toml"); + fs::write(&snake, "max_git_depth: 0\n").unwrap(); + fs::write(&kebab, "max-git-depth = 7\n").unwrap(); + + assert_eq!(depth_after_defaults(Some(&snake)), 0); + assert_eq!(depth_after_defaults(Some(&kebab)), 7); + } +} diff --git a/src/defaults.rs b/src/defaults.rs index fa068dc7..e3994ba8 100644 --- a/src/defaults.rs +++ b/src/defaults.rs @@ -158,3 +158,6 @@ pub const DEFAULT_IGNORE_PATTERNS: &[&str] = &[ ]; pub const DEFAULT_OUTPUT_TEMPLATE: &str = ">>>> FILE_PATH\nFILE_CONTENT"; + +/// Number of most recent commits scanned for the Git recency boost. +pub const DEFAULT_MAX_GIT_DEPTH: i32 = 100; diff --git a/src/lib.rs b/src/lib.rs index 7ac58885..7e92003f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -59,6 +59,37 @@ pub fn is_text_file(path: &Path, user_binary_extensions: &[String]) -> io::Resul Ok(inspect(&buf) != ContentType::BINARY) } +/// Gather last-commit times for every input directory that lives in a Git repo. +/// +/// Git reports paths relative to the repository root, while files are later +/// processed relative to each input path. Keying by canonical absolute path +/// lets the two meet regardless of which subdirectory the user passed in. +fn collect_commit_times(config: &YekConfig) -> HashMap { + let max_commits = config.max_git_depth.try_into().unwrap_or(0); + config + .input_paths + .par_iter() + .filter_map(|path_str| { + let input_dir = Path::new(path_str); + if !input_dir.is_dir() { + return None; + } + // An absolute path lets repo discovery walk up from a subdirectory. + let input_dir = input_dir.canonicalize().ok()?; + let (repo_root, times) = + priority::get_recent_commit_times_with_root(&input_dir, max_commits)?; + let repo_root = repo_root.canonicalize().unwrap_or(repo_root); + Some( + times + .into_iter() + .map(|(rel, time)| (repo_root.join(rel).to_string_lossy().into_owned(), time)) + .collect::>(), + ) + }) + .flatten() + .collect() +} + /// Main entrypoint for serialization, used by CLI and tests pub fn serialize_repo(config: &YekConfig) -> Result<(String, Vec)> { // Validate input paths and warn about non-existent ones @@ -79,25 +110,9 @@ pub fn serialize_repo(config: &YekConfig) -> Result<(String, Vec) } } - // Gather commit times from each input path that is a directory - let combined_commit_times = config - .input_paths - .par_iter() - .filter_map(|path_str| { - let repo_path = Path::new(path_str); - if repo_path.is_dir() { - priority::get_recent_commit_times_git2( - repo_path, - config.max_git_depth.try_into().unwrap_or(0), - ) - } else { - None - } - }) - .flatten() - .collect::>(); + let combined_commit_times = collect_commit_times(config); - // Compute a recentness-based boost + // Compute a recentness-based boost, keyed by canonical absolute file path let recentness_boost = compute_recentness_boost(&combined_commit_times, config.git_boost_max.unwrap_or(100)); diff --git a/src/parallel.rs b/src/parallel.rs index d3c84fcc..7cb08399 100644 --- a/src/parallel.rs +++ b/src/parallel.rs @@ -9,7 +9,7 @@ use path_slash::PathBufExt; use rayon::prelude::*; use std::{ collections::HashMap, - path::Path, + path::{Path, PathBuf}, sync::{Arc, Mutex}, time::Instant, }; @@ -19,6 +19,8 @@ use tracing::debug; pub struct ParallelFileProcessor { context: Arc, file_counter: Arc>>, + /// Git recency boost keyed by canonical absolute file path. + recentness_boost: HashMap, } impl ParallelFileProcessor { @@ -26,6 +28,19 @@ impl ParallelFileProcessor { Self { context: Arc::new(context), file_counter: Arc::new(Mutex::new(HashMap::new())), + recentness_boost: HashMap::new(), + } + } + + /// Apply a Git recency boost, keyed by canonical absolute file path. + pub fn with_recentness_boost(self, boost_map: &HashMap) -> Self { + let recentness_boost = boost_map + .iter() + .map(|(path, boost)| (PathBuf::from(path), *boost)) + .collect(); + Self { + recentness_boost, + ..self } } @@ -195,7 +210,8 @@ impl ParallelFileProcessor { debug!("Skipping binary file: {rel_path}"); Ok(Vec::new()) } else { - let processed_file = self.create_processed_file(&rel_path, &content)?; + let processed_file = + self.create_processed_file(file_path, &rel_path, &content)?; Ok(vec![processed_file]) } } @@ -291,7 +307,7 @@ impl ParallelFileProcessor { } // Calculate priority with category - let (priority, category) = self.calculate_priority_with_category(rel_path); + let (priority, category) = self.calculate_priority_with_category(file_path, rel_path); // Get thread-safe file index let file_index = self.get_next_file_index(priority); @@ -335,6 +351,7 @@ impl ParallelFileProcessor { /// Calculate priority for a file including category-based offset fn calculate_priority_with_category( &self, + file_path: &Path, rel_path: &str, ) -> (i32, crate::category::FileCategory) { use crate::priority::get_file_priority_with_category; @@ -346,19 +363,23 @@ impl ParallelFileProcessor { &self.context.processing_config.category_weights, ); - // Apply git boost if available - if let Some(commit_time) = self.context.repository_info.commit_times.get(rel_path) { - let max_boost = self.context.input_config.git_boost_max.unwrap_or(100); - priority += self.calculate_git_boost( - *commit_time, - &self.context.repository_info.commit_times, - max_boost, - ); - } + priority += self.recentness_boost_for(file_path); (priority, category) } + /// Look up the Git recency boost for a file, or 0 when it has none. + fn recentness_boost_for(&self, file_path: &Path) -> i32 { + if self.recentness_boost.is_empty() { + return 0; + } + file_path + .canonicalize() + .ok() + .and_then(|path| self.recentness_boost.get(&path).copied()) + .unwrap_or(0) + } + /// Calculate git boost for a file fn calculate_git_boost( &self, @@ -431,8 +452,13 @@ impl ParallelFileProcessor { } /// Create a processed file with proper metadata - fn create_processed_file(&self, rel_path: &str, content: &[u8]) -> Result { - let (priority, category) = self.calculate_priority_with_category(rel_path); + fn create_processed_file( + &self, + file_path: &Path, + rel_path: &str, + content: &[u8], + ) -> Result { + let (priority, category) = self.calculate_priority_with_category(file_path, rel_path); let file_index = self.get_next_file_index(priority); Ok(ProcessedFile::new_with_category( @@ -465,11 +491,13 @@ pub fn normalize_path(path: &Path, base: &Path) -> String { .to_string() } -/// Legacy function for backward compatibility - delegates to new implementation +/// Legacy function for backward compatibility - delegates to new implementation. +/// +/// `boost_map` holds the Git recency boost keyed by canonical absolute file path. pub fn process_files_parallel( base_path: &Path, config: &crate::config::YekConfig, - _boost_map: &HashMap, + boost_map: &HashMap, ) -> Result> { // This is a temporary bridge - in the final implementation, // this would be replaced with the new pipeline-based approach @@ -497,7 +525,8 @@ pub fn process_files_parallel( }, crate::models::RepositoryInfo::new(base_path.to_path_buf(), false), // TODO: Proper repo info Arc::new(crate::repository::RealFileSystem), - )); + )) + .with_recentness_boost(boost_map); processor.process_files_parallel(base_path) } diff --git a/src/priority.rs b/src/priority.rs index 3a90904c..26387eda 100644 --- a/src/priority.rs +++ b/src/priority.rs @@ -1,7 +1,10 @@ use git2; use regex; use serde::{Deserialize, Serialize}; -use std::{collections::HashMap, path::Path}; +use std::{ + collections::HashMap, + path::{Path, PathBuf}, +}; use tracing::debug; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] @@ -96,11 +99,21 @@ pub fn compute_recentness_boost( /// Get the commit time of the most recent change to each file using git2. /// Returns a map from file path (relative to the repo root) → last commit Unix time. /// If Git or .git folder is missing, returns None instead of erroring. -/// Only considers up to `max_commits` most recent commits. +/// Only considers up to `max_commits` most recent commits; files not changed +/// within that window are left out of the map. pub fn get_recent_commit_times_git2( repo_path: &Path, max_commits: usize, ) -> Option> { + get_recent_commit_times_with_root(repo_path, max_commits).map(|(_, times)| times) +} + +/// Like [`get_recent_commit_times_git2`], but also returns the repository's +/// working-directory root, which the returned paths are relative to. +pub fn get_recent_commit_times_with_root( + repo_path: &Path, + max_commits: usize, +) -> Option<(PathBuf, HashMap)> { // Walk up until you find a .git folder but not higher than the base of the given repo_path let mut current_path = repo_path.to_path_buf(); while current_path.components().count() > 1 { @@ -160,18 +173,30 @@ pub fn get_recent_commit_times_git2( } }; + // Only the files this commit actually changed get its time. Walking the + // whole tree instead would stamp every file in HEAD with HEAD's time. + let parent_tree = commit.parent(0).ok().and_then(|p| p.tree().ok()); + let diff = match repo.diff_tree_to_tree(parent_tree.as_ref(), Some(&tree), None) { + Ok(diff) => diff, + Err(e) => { + debug!("Failed to diff commit {:?}: {:?}", oid, e); + continue; + } + }; + let time = commit.time().seconds() as u64; - tree.walk(git2::TreeWalkMode::PreOrder, |root, entry| { - if let Some(name) = entry.name() { - if entry.kind() == Some(git2::ObjectType::Blob) { - let full_path = format!("{}{}", root, name); - commit_times.entry(full_path).or_insert(time); - } + for delta in diff.deltas() { + if delta.status() == git2::Delta::Deleted { + continue; + } + if let Some(path) = delta.new_file().path() { + commit_times + .entry(path.to_string_lossy().into_owned()) + .or_insert(time); } - git2::TreeWalkResult::Ok - }) - .ok()?; + } } - Some(commit_times) + let repo_root = repo.workdir()?.to_path_buf(); + Some((repo_root, commit_times)) } diff --git a/tests/git_boost_test.rs b/tests/git_boost_test.rs new file mode 100644 index 00000000..9d060ed2 --- /dev/null +++ b/tests/git_boost_test.rs @@ -0,0 +1,139 @@ +#[cfg(test)] +mod git_boost_tests { + use std::fs; + use std::path::Path; + use std::process::Command; + use tempfile::tempdir; + use yek::{config::YekConfig, models::ProcessedFile, serialize_repo}; + + const OLD_COMMIT_DATE: &str = "2020-01-01T00:00:00+0000"; + const NEW_COMMIT_DATE: &str = "2024-01-01T00:00:00+0000"; + + fn git(repo: &Path, args: &[&str], date: &str) { + let status = Command::new("git") + .args(args) + .current_dir(repo) + .env("GIT_AUTHOR_NAME", "Test") + .env("GIT_AUTHOR_EMAIL", "test@example.com") + .env("GIT_COMMITTER_NAME", "Test") + .env("GIT_COMMITTER_EMAIL", "test@example.com") + .env("GIT_AUTHOR_DATE", date) + .env("GIT_COMMITTER_DATE", date) + .status() + .expect("git must be installed to run these tests"); + assert!(status.success(), "git {:?} failed", args); + } + + /// Commits `old` in 2020 and `new` in 2024, both under `subdir` of a fresh repo. + fn repo_with_old_and_new_file(repo: &Path, subdir: &str, old: &str, new: &str) { + let dir = repo.join(subdir); + fs::create_dir_all(&dir).unwrap(); + git(repo, &["init", "-q"], OLD_COMMIT_DATE); + + fs::write(dir.join(old), "old content").unwrap(); + git(repo, &["add", "."], OLD_COMMIT_DATE); + git(repo, &["commit", "-q", "-m", "old"], OLD_COMMIT_DATE); + + fs::write(dir.join(new), "new content").unwrap(); + git(repo, &["add", "."], NEW_COMMIT_DATE); + git(repo, &["commit", "-q", "-m", "new"], NEW_COMMIT_DATE); + } + + fn config_for(input: &Path, git_boost_max: Option) -> YekConfig { + let mut config = YekConfig::extend_config_with_defaults( + vec![input.to_string_lossy().to_string()], + std::env::temp_dir().to_string_lossy().to_string(), + ); + config.git_boost_max = git_boost_max; + config + } + + fn priority_of(files: &[ProcessedFile], rel_path: &str) -> i32 { + files + .iter() + .find(|f| f.rel_path == rel_path) + .unwrap_or_else(|| panic!("{rel_path} missing from output")) + .priority + } + + #[test] + fn recently_committed_file_gets_higher_priority_than_old_file() { + let repo = tempdir().unwrap(); + // `a_new` sorts before `z_old` by name, so only the boost can put it last. + repo_with_old_and_new_file(repo.path(), ".", "z_old.txt", "a_new.txt"); + + let (output, files) = serialize_repo(&config_for(repo.path(), Some(100))).unwrap(); + + assert_eq!( + priority_of(&files, "a_new.txt") - priority_of(&files, "z_old.txt"), + 100 + ); + let old_pos = output.find("z_old.txt").unwrap(); + let new_pos = output.find("a_new.txt").unwrap(); + assert!( + old_pos < new_pos, + "the recently changed file must come last in the output" + ); + } + + #[test] + fn boost_applies_when_input_is_a_subdirectory_of_the_repo() { + let repo = tempdir().unwrap(); + repo_with_old_and_new_file(repo.path(), "pkg", "z_old.txt", "a_new.txt"); + + let (_, files) = serialize_repo(&config_for(&repo.path().join("pkg"), Some(100))).unwrap(); + + assert_eq!( + priority_of(&files, "a_new.txt") - priority_of(&files, "z_old.txt"), + 100 + ); + } + + #[test] + fn zero_git_boost_max_leaves_priorities_equal() { + let repo = tempdir().unwrap(); + repo_with_old_and_new_file(repo.path(), ".", "z_old.txt", "a_new.txt"); + + let (_, files) = serialize_repo(&config_for(repo.path(), Some(0))).unwrap(); + + assert_eq!( + priority_of(&files, "a_new.txt"), + priority_of(&files, "z_old.txt") + ); + } + + #[test] + fn cli_puts_recently_committed_file_last_without_any_config() { + let repo = tempdir().unwrap(); + repo_with_old_and_new_file(repo.path(), ".", "z_old.txt", "a_new.txt"); + + let output = assert_cmd::Command::cargo_bin("yek") + .unwrap() + .current_dir(repo.path()) + .arg(".") + .output() + .unwrap(); + let stdout = String::from_utf8(output.stdout).unwrap(); + + let old_pos = stdout.find(">>>> z_old.txt").expect("z_old.txt missing"); + let new_pos = stdout.find(">>>> a_new.txt").expect("a_new.txt missing"); + assert!( + old_pos < new_pos, + "the recently changed file must come last, got:\n{stdout}" + ); + } + + #[test] + fn directory_without_git_history_gets_no_boost() { + let dir = tempdir().unwrap(); + fs::write(dir.path().join("one.txt"), "1").unwrap(); + fs::write(dir.path().join("two.txt"), "2").unwrap(); + + let (_, files) = serialize_repo(&config_for(dir.path(), Some(100))).unwrap(); + + assert_eq!( + priority_of(&files, "one.txt"), + priority_of(&files, "two.txt") + ); + } +} diff --git a/tests/priority_test.rs b/tests/priority_test.rs index 175f48e8..b358afa2 100644 --- a/tests/priority_test.rs +++ b/tests/priority_test.rs @@ -222,6 +222,41 @@ mod priority_tests { assert!(times.contains_key("file2.txt")); } + #[test] + fn commit_time_is_when_the_file_last_changed_not_the_head_commit() { + let dir = tempdir().unwrap(); + let repo_path = dir.path(); + let git = |args: &[&str], date: &str| { + let status = std::process::Command::new("git") + .args(args) + .current_dir(repo_path) + .env("GIT_AUTHOR_NAME", "Test") + .env("GIT_AUTHOR_EMAIL", "test@example.com") + .env("GIT_COMMITTER_NAME", "Test") + .env("GIT_COMMITTER_EMAIL", "test@example.com") + .env("GIT_AUTHOR_DATE", date) + .env("GIT_COMMITTER_DATE", date) + .status() + .unwrap(); + assert!(status.success(), "git {:?} failed", args); + }; + let old_date = "2020-01-01T00:00:00+0000"; + let new_date = "2024-01-01T00:00:00+0000"; + + git(&["init", "-q"], old_date); + fs::write(repo_path.join("old.txt"), "old").unwrap(); + git(&["add", "."], old_date); + git(&["commit", "-q", "-m", "old"], old_date); + fs::write(repo_path.join("new.txt"), "new").unwrap(); + git(&["add", "."], new_date); + git(&["commit", "-q", "-m", "new"], new_date); + + let times = get_recent_commit_times_git2(repo_path, 100).unwrap(); + + assert_eq!(times.get("old.txt"), Some(&1_577_836_800)); // 2020-01-01 + assert_eq!(times.get("new.txt"), Some(&1_704_067_200)); // 2024-01-01 + } + #[test] fn test_get_recent_commit_times_empty_repo() { let dir = tempdir().unwrap(); From c294a9a7e2b6cd5c529ab08072946f9b0f1cafbf Mon Sep 17 00:00:00 2001 From: Sahib Yar Date: Sun, 29 Nov 2026 18:37:04 +0500 Subject: [PATCH 2/4] perf: compile priority rule regexes once per run get_file_priority compiled every rule's regex on each call, and the parallel processor called it once per file, so a run did files x rules regex compilations. Add CompiledPriorityRules, built once when the processor is created, and score every file against it. get_file_priority and get_file_priority_with_category keep their signatures and delegate to it. 20,000 files with 10 rules (release build, 5 runs): ~2.3s -> ~0.19s. Output is byte-for-byte identical. Fixes #273 --- src/parallel.rs | 11 +++++--- src/priority.rs | 62 +++++++++++++++++++++++++++++++++++------- tests/priority_test.rs | 41 ++++++++++++++++++++++++++++ 3 files changed, 100 insertions(+), 14 deletions(-) diff --git a/src/parallel.rs b/src/parallel.rs index 7cb08399..67007bba 100644 --- a/src/parallel.rs +++ b/src/parallel.rs @@ -1,6 +1,7 @@ use crate::{ models::{InputConfig, OutputConfig, ProcessedFile, ProcessingConfig}, pipeline::ProcessingContext, + priority::{get_compiled_file_priority_with_category, CompiledPriorityRules}, }; use anyhow::{anyhow, Result}; use content_inspector::{inspect, ContentType}; @@ -21,11 +22,15 @@ pub struct ParallelFileProcessor { file_counter: Arc>>, /// Git recency boost keyed by canonical absolute file path. recentness_boost: HashMap, + /// Priority rules compiled once instead of once per file. + priority_rules: CompiledPriorityRules, } impl ParallelFileProcessor { pub fn new(context: ProcessingContext) -> Self { + let priority_rules = CompiledPriorityRules::new(&context.processing_config.priority_rules); Self { + priority_rules, context: Arc::new(context), file_counter: Arc::new(Mutex::new(HashMap::new())), recentness_boost: HashMap::new(), @@ -354,12 +359,10 @@ impl ParallelFileProcessor { file_path: &Path, rel_path: &str, ) -> (i32, crate::category::FileCategory) { - use crate::priority::get_file_priority_with_category; - // Get base priority from rules and category - let (mut priority, category) = get_file_priority_with_category( + let (mut priority, category) = get_compiled_file_priority_with_category( rel_path, - &self.context.processing_config.priority_rules, + &self.priority_rules, &self.context.processing_config.category_weights, ); diff --git a/src/priority.rs b/src/priority.rs index 26387eda..1248afc7 100644 --- a/src/priority.rs +++ b/src/priority.rs @@ -13,18 +13,47 @@ pub struct PriorityRule { pub score: i32, } +/// Priority rules with their patterns compiled once, for scoring many files. +/// +/// Rules whose pattern is not a valid regex are skipped, matching +/// [`get_file_priority`]. +#[derive(Debug, Clone)] +pub struct CompiledPriorityRules { + rules: Vec<(regex::Regex, i32)>, +} + +impl CompiledPriorityRules { + pub fn new(rules: &[PriorityRule]) -> Self { + let rules = rules + .iter() + .filter_map(|rule| match regex::Regex::new(&rule.pattern) { + Ok(re) => Some((re, rule.score)), + Err(e) => { + debug!("Skipping invalid priority pattern {:?}: {e}", rule.pattern); + None + } + }) + .collect(); + Self { rules } + } + + /// Sum of the scores of every rule whose pattern matches `path`. + pub fn score(&self, path: &str) -> i32 { + self.rules + .iter() + .filter(|(re, _)| re.is_match(path)) + .map(|(_, score)| score) + .sum() + } +} + /// Determine final priority of a file by scanning the priority list /// in descending order of score. +/// +/// Compiles every pattern on each call; when scoring many files, build a +/// [`CompiledPriorityRules`] once instead. pub fn get_file_priority(path: &str, rules: &[PriorityRule]) -> i32 { - let mut priority = 0; - for rule in rules { - if let Ok(re) = regex::Regex::new(&rule.pattern) { - if re.is_match(path) { - priority += rule.score; - } - } - } - priority + CompiledPriorityRules::new(rules).score(path) } /// Calculate file priority including category-based offset @@ -32,9 +61,22 @@ pub fn get_file_priority_with_category( path: &str, rules: &[PriorityRule], category_weights: &crate::category::CategoryWeights, +) -> (i32, crate::category::FileCategory) { + get_compiled_file_priority_with_category( + path, + &CompiledPriorityRules::new(rules), + category_weights, + ) +} + +/// Like [`get_file_priority_with_category`], with the rules compiled up front. +pub fn get_compiled_file_priority_with_category( + path: &str, + rules: &CompiledPriorityRules, + category_weights: &crate::category::CategoryWeights, ) -> (i32, crate::category::FileCategory) { let category = crate::category::categorize_file(path); - let rule_priority = get_file_priority(path, rules); + let rule_priority = rules.score(path); let category_offset = category_weights.get_offset(category); let total_priority = rule_priority + category_offset; diff --git a/tests/priority_test.rs b/tests/priority_test.rs index b358afa2..9d478716 100644 --- a/tests/priority_test.rs +++ b/tests/priority_test.rs @@ -764,3 +764,44 @@ fn test_get_recent_commit_times_git_with_submodules() { // Should handle repos with submodules configuration assert!(times.is_none() || times.unwrap().is_empty()); } + +mod compiled_priority_rules_tests { + use yek::priority::{get_file_priority, CompiledPriorityRules, PriorityRule}; + + fn rule(pattern: &str, score: i32) -> PriorityRule { + PriorityRule { + pattern: pattern.to_string(), + score, + } + } + + #[test] + fn sums_scores_of_every_matching_rule() { + let compiled = CompiledPriorityRules::new(&[rule("^src/", 5), rule(r"\.rs$", 10)]); + + assert_eq!(compiled.score("src/main.rs"), 15); + assert_eq!(compiled.score("src/README.md"), 5); + assert_eq!(compiled.score("docs/guide.md"), 0); + } + + #[test] + fn skips_rules_with_invalid_patterns() { + let compiled = CompiledPriorityRules::new(&[rule("[unclosed", 99), rule("main", 1)]); + + assert_eq!(compiled.score("main.rs"), 1); + } + + #[test] + fn matches_uncompiled_scoring_for_the_same_rules() { + let rules = [rule("^src/", 5), rule(r"\.rs$", 10), rule("test", -3)]; + let compiled = CompiledPriorityRules::new(&rules); + + for path in ["src/main.rs", "tests/test_x.rs", "README.md", "src/test.md"] { + assert_eq!( + compiled.score(path), + get_file_priority(path, &rules), + "{path}" + ); + } + } +} From 1a8c350381250de4b0a6183d522fcade533ec634 Mon Sep 17 00:00:00 2001 From: Sahib Yar Date: Sun, 29 Nov 2026 18:57:50 +0500 Subject: [PATCH 3/4] fix: drop files whose latest change deleted them from commit times A file deleted in a newer commit was skipped there, then picked up again from the older commit that added it. Deleted paths stayed in the map and widened the oldest/newest range that the recency boost is normalised over. The newest commit touching a path now decides its entry, and a deletion records no time. Also cover modifications and the max_git_depth commit window. Refs #272 --- src/priority.rs | 16 +++--- tests/priority_test.rs | 119 +++++++++++++++++++++++++++++++---------- 2 files changed, 101 insertions(+), 34 deletions(-) diff --git a/src/priority.rs b/src/priority.rs index 1248afc7..e919e8fd 100644 --- a/src/priority.rs +++ b/src/priority.rs @@ -190,7 +190,9 @@ pub fn get_recent_commit_times_with_root( } revwalk.set_sorting(git2::Sort::TIME).ok()?; - let mut commit_times = HashMap::new(); + // The newest commit touching a path decides its entry; `None` marks a + // path whose newest change was a deletion, so older commits can't revive it. + let mut latest_change: HashMap> = HashMap::new(); for oid_result in revwalk.take(max_commits) { let oid = match oid_result { Ok(oid) => oid, @@ -228,17 +230,19 @@ pub fn get_recent_commit_times_with_root( let time = commit.time().seconds() as u64; for delta in diff.deltas() { - if delta.status() == git2::Delta::Deleted { - continue; - } + let deleted = delta.status() == git2::Delta::Deleted; if let Some(path) = delta.new_file().path() { - commit_times + latest_change .entry(path.to_string_lossy().into_owned()) - .or_insert(time); + .or_insert((!deleted).then_some(time)); } } } + let commit_times = latest_change + .into_iter() + .filter_map(|(path, time)| time.map(|t| (path, t))) + .collect(); let repo_root = repo.workdir()?.to_path_buf(); Some((repo_root, commit_times)) } diff --git a/tests/priority_test.rs b/tests/priority_test.rs index 9d478716..27b93e6d 100644 --- a/tests/priority_test.rs +++ b/tests/priority_test.rs @@ -222,39 +222,102 @@ mod priority_tests { assert!(times.contains_key("file2.txt")); } + const DATE_2020: &str = "2020-01-01T00:00:00+0000"; + const DATE_2022: &str = "2022-01-01T00:00:00+0000"; + const DATE_2024: &str = "2024-01-01T00:00:00+0000"; + const UNIX_2020: u64 = 1_577_836_800; + const UNIX_2022: u64 = 1_640_995_200; + const UNIX_2024: u64 = 1_704_067_200; + + /// Runs git in `repo` with a fixed identity and author/commit date. + fn git_at(repo: &std::path::Path, args: &[&str], date: &str) { + let status = std::process::Command::new("git") + .args(args) + .current_dir(repo) + .env("GIT_AUTHOR_NAME", "Test") + .env("GIT_AUTHOR_EMAIL", "test@example.com") + .env("GIT_COMMITTER_NAME", "Test") + .env("GIT_COMMITTER_EMAIL", "test@example.com") + .env("GIT_AUTHOR_DATE", date) + .env("GIT_COMMITTER_DATE", date) + .status() + .unwrap(); + assert!(status.success(), "git {:?} failed", args); + } + + fn commit_all(repo: &std::path::Path, date: &str) { + git_at(repo, &["add", "-A"], date); + git_at(repo, &["commit", "-q", "-m", date], date); + } + #[test] fn commit_time_is_when_the_file_last_changed_not_the_head_commit() { let dir = tempdir().unwrap(); - let repo_path = dir.path(); - let git = |args: &[&str], date: &str| { - let status = std::process::Command::new("git") - .args(args) - .current_dir(repo_path) - .env("GIT_AUTHOR_NAME", "Test") - .env("GIT_AUTHOR_EMAIL", "test@example.com") - .env("GIT_COMMITTER_NAME", "Test") - .env("GIT_COMMITTER_EMAIL", "test@example.com") - .env("GIT_AUTHOR_DATE", date) - .env("GIT_COMMITTER_DATE", date) - .status() - .unwrap(); - assert!(status.success(), "git {:?} failed", args); - }; - let old_date = "2020-01-01T00:00:00+0000"; - let new_date = "2024-01-01T00:00:00+0000"; - - git(&["init", "-q"], old_date); - fs::write(repo_path.join("old.txt"), "old").unwrap(); - git(&["add", "."], old_date); - git(&["commit", "-q", "-m", "old"], old_date); - fs::write(repo_path.join("new.txt"), "new").unwrap(); - git(&["add", "."], new_date); - git(&["commit", "-q", "-m", "new"], new_date); + let repo = dir.path(); + git_at(repo, &["init", "-q"], DATE_2020); + fs::write(repo.join("old.txt"), "old").unwrap(); + commit_all(repo, DATE_2020); + fs::write(repo.join("new.txt"), "new").unwrap(); + commit_all(repo, DATE_2024); - let times = get_recent_commit_times_git2(repo_path, 100).unwrap(); + let times = get_recent_commit_times_git2(repo, 100).unwrap(); + + assert_eq!(times.get("old.txt"), Some(&UNIX_2020)); + assert_eq!(times.get("new.txt"), Some(&UNIX_2024)); + } + + #[test] + fn commit_time_follows_the_latest_modification_of_a_file() { + let dir = tempdir().unwrap(); + let repo = dir.path(); + git_at(repo, &["init", "-q"], DATE_2020); + fs::create_dir(repo.join("src")).unwrap(); + fs::write(repo.join("src/edited.rs"), "v1").unwrap(); + fs::write(repo.join("untouched.txt"), "same").unwrap(); + commit_all(repo, DATE_2020); + fs::write(repo.join("src/edited.rs"), "v2").unwrap(); + commit_all(repo, DATE_2022); + + let times = get_recent_commit_times_git2(repo, 100).unwrap(); + + assert_eq!(times.get("src/edited.rs"), Some(&UNIX_2022)); + assert_eq!(times.get("untouched.txt"), Some(&UNIX_2020)); + } + + #[test] + fn deleted_files_get_no_commit_time() { + let dir = tempdir().unwrap(); + let repo = dir.path(); + git_at(repo, &["init", "-q"], DATE_2020); + fs::write(repo.join("kept.txt"), "kept").unwrap(); + fs::write(repo.join("gone.txt"), "gone").unwrap(); + commit_all(repo, DATE_2020); + fs::remove_file(repo.join("gone.txt")).unwrap(); + commit_all(repo, DATE_2024); + + let times = get_recent_commit_times_git2(repo, 100).unwrap(); + + assert_eq!(times.get("kept.txt"), Some(&UNIX_2020)); + assert!( + !times.contains_key("gone.txt"), + "a deleted file must not get the deleting commit's time" + ); + } + + #[test] + fn files_changed_only_before_the_commit_window_are_left_out() { + let dir = tempdir().unwrap(); + let repo = dir.path(); + git_at(repo, &["init", "-q"], DATE_2020); + fs::write(repo.join("ancient.txt"), "a").unwrap(); + commit_all(repo, DATE_2020); + fs::write(repo.join("recent.txt"), "r").unwrap(); + commit_all(repo, DATE_2024); + + let times = get_recent_commit_times_git2(repo, 1).unwrap(); - assert_eq!(times.get("old.txt"), Some(&1_577_836_800)); // 2020-01-01 - assert_eq!(times.get("new.txt"), Some(&1_704_067_200)); // 2024-01-01 + assert_eq!(times.get("recent.txt"), Some(&UNIX_2024)); + assert!(!times.contains_key("ancient.txt")); } #[test] From cfff63bc506951e23d394973fd9e7fdde544f8e3 Mon Sep 17 00:00:00 2001 From: Sahib Yar Date: Sun, 29 Nov 2026 18:57:50 +0500 Subject: [PATCH 4/4] ci: check out PR and base commits by SHA The benchmark and coverage jobs ran `git checkout ${{ github.head_ref }}`. For pull requests from forks that branch does not exist in this repository, so both jobs failed with "pathspec did not match". `git fetch origin main` also resolved to the tag named `main` (an old v0.21 commit) instead of the branch, so baselines were measured against the wrong code. Check out github.event.pull_request.base.sha and github.sha instead, which are unambiguous and work for forks. --- .github/workflows/ci.yml | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 482f1017..fe3d3527 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -213,12 +213,13 @@ jobs: - name: Run benchmarks run: | - git fetch origin ${{ github.base_ref }} - git checkout ${{ github.base_ref }} + # Check out by SHA: the PR branch does not exist in this repo for + # fork PRs, and a tag named like the base branch would shadow it. + git checkout --detach ${{ github.event.pull_request.base.sha }} cargo bench --bench serialization --no-run cargo bench --bench serialization -- --save-baseline ${{ github.base_ref }} '${{ matrix.benchmark_group.group }}/' - git checkout ${{ github.head_ref }} + git checkout --detach ${{ github.sha }} cargo bench --bench serialization --no-run cargo bench --bench serialization -- --baseline ${{ github.base_ref }} --noise-threshold 2 '${{ matrix.benchmark_group.group }}/' > benchmark_results.md echo "## Benchmark Results for ${{ matrix.benchmark_group.name }}" >> $GITHUB_STEP_SUMMARY @@ -260,9 +261,10 @@ jobs: # --- Base Branch Coverage --- - name: Fetch and check out base branch if: github.event_name == 'pull_request' + # Check out by SHA: the PR branch does not exist in this repo for + # fork PRs, and a tag named like the base branch would shadow it. run: | - git fetch origin ${{ github.base_ref }} - git checkout ${{ github.base_ref }} + git checkout --detach ${{ github.event.pull_request.base.sha }} - name: Build + Test coverage on base if: github.event_name == 'pull_request' @@ -294,7 +296,7 @@ jobs: - name: Check out head branch (PR) if: github.event_name == 'pull_request' run: | - git checkout ${{ github.head_ref }} + git checkout --detach ${{ github.sha }} - name: Build + Test coverage on PR run: |